我正在使用simple_form,我只想使用分类表在类别和文章之间创建关联。

但是我有这个错误:
无法批量分配受保护的属性:category_ids。
app / controllers / articles_controller.rb:36:在“更新”中

article_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 %>

最佳答案

在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

关于ruby-on-rails - 无法批量分配 protected 属性:category_ids,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11493684/

10-09 02:55