我正在使用simple_form,我只想使用分类表在类别和文章之间创建关联。
但我有这个错误: 无法批量分配受保护的属性:category_ids。 app / controllers / articles_controller.rb:36:在`update'
articles_controller.rb
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article]) ---line with the problem
flash[:success] = "Статья обновлена"
redirect_to @article
else
render :edit
end
end
article.rb
has_many :categorizations
has_many :categories, through: :categorizations
category.rb
has_many :categorizations
has_many :articles, through: :categorizations
categorization.rb
belongs_to :article
belongs_to :category
分类包含article_id和category_id字段。
我的_form.html.erb
<%= simple_form_for @article, html: { class: "form-horizontal", multipart: true } do |f| %>
<%= f.error_notification %>
<%= f.input :title %>
<%= f.association :categories %>
<%= f.input :teaser %>
<%= f.input :body %>
<%= f.input :published %>
<% if @article.published? %>
<%= f.button :submit, value: "Внести изменения" %>
<% else %>
<%= f.button :submit, value: "Опубликовать" %>
<% end %>
<% end %>
答案 0 :(得分:5)
你在article.rb中有attr_accessible吗?
如果是这样添加
attr_accessible :title, :category_ids
另外请确保您真的想要所有表格...如果不是这样:
attr_accessible :title, :category_ids, :as => :admin
然后
@article = Article.new
@article.assign_attributes({ :category_ids => [1,2], :title => 'hello' })
@article.category_ids # => []
@article.title # => 'hello'
@article.assign_attributes({ :category_ids => [1,2], :title => 'hello' }, :as => :admin)
@article.category_ids # => [1,2]
@article.title # => 'hello'
@article.save
或
@article = Article.new({ :category_ids => [1,2], :title => 'hello' })
@article.category_ids # => []
@article.title # => 'hello'
@article = Article.new({ :category_ids => [1,2], :title => 'hello' }, :as => :admin)
@article.category_ids # => [1,2]
@article.title # => 'hello'
@article.save
答案 1 :(得分:3)
创建的表单字段
<%= f.association :categories %>
将设置属性category_id
,但该属性受到保护。在你的模型中,你应该有一行代码如下:
attr_accessible :title, :teaser, :body, :published
允许这些属性进行质量分配。如果您希望表单设置category_id
,则必须将这些属性添加到attr_accessible
方法中:
attr_accessible :title, :teaser, :body, :published, :category_id
这可以解决您的问题。