0
我有一個問題,在我的簡單表單中向文章添加分類。 這些類別顯示在simple_form_for中,但category_id在創建時並不歸因於文章! (params?)問題在Rails中向文章添加分類
Tx對你有幫助!
我已經創建了兩個模型
class Category < ApplicationRecord
has_many :articles
end
class Article < ApplicationRecord
belongs_to :category
has_attachments :photos, maximum: 2
end
和他們
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "card_summary"
t.text "summary"
t.integer "category_id"
t.index ["category_id"], name: "index_articles_on_category_id", using: :btree
end
之間的外鍵的文章控制器創建一個文章
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to article_path(@article)
else
render :new
end
end
private
def article_params
params.require(:article).permit(:title, :card_summary, :summary, :body, photos: [])
end
,並在那裏我用F中的simple_form_for 。關聯(正確顯示不同類別)
<%= simple_form_for @article do |f| %>
<%= f.input :title %>
<%= f.input :card_summary %>
<%= f.input :summary %>
<%= f.input :photos, as: :attachinary %>
<%= f.input :body %>
<%= f.association :category %>
<%= f.submit "Soumettre un article", class: "btn btn-primary" %>
<% end %>
我認爲我的分貝是好的,因爲我可以用控制檯將一個分類歸類到一篇文章,但是我被卡在了這個表格中。任何幫助將非常感激。 THX愛德華
編輯
這裏是我的遷移。哪裏不對了?
class AddCategoryReferenceToArticles < ActiveRecord::Migration[5.0]
def change
add_reference :articles, :category, foreign_key: true, index: true
end
end
是不是在您的PARAMS'.permit(:標題,:card_summary,:總結,:身體,照片:[]',也不在你的窗體中,但在你的遷移中出現'category_id'。 –
這是我的遷移 – Edouard