在Rails中向Article添加类别的问题

时间:2017-06-14 13:50:02

标签: ruby-on-rails associations strong-parameters simple-form-for

我在以简单形式向文章添加类别时遇到问题。 类别显示在simple_form_for中,但category_id在创建时不归因于文章! (params?)

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.association的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 Edouard

修改

这是我的迁移。怎么了?

class AddCategoryReferenceToArticles < ActiveRecord::Migration[5.0]
  def change
    add_reference :articles, :category, foreign_key: true, index: true
  end
end

1 个答案:

答案 0 :(得分:0)

category_id中添加article_params可以解决问题

def article_params
  params.require(:article).permit(:title, :card_summary, :summary, :category_id, photos: [])
end