无法批量分配受保护的属性:category_ids

ich*_*kov 3 ruby-on-rails associations nested-forms ruby-on-rails-3 simple-form

我正在使用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
Run Code Online (Sandbox Code Playgroud)

article.rb

has_many :categorizations
has_many :categories, through: :categorizations
Run Code Online (Sandbox Code Playgroud)

category.rb

has_many :categorizations
has_many :articles, through: :categorizations
Run Code Online (Sandbox Code Playgroud)

categorization.rb

belongs_to :article
belongs_to :category
Run Code Online (Sandbox Code Playgroud)

分类有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 %>
Run Code Online (Sandbox Code Playgroud)

drh*_*ner 5

你在article.rb中有attr_accessible吗?

如果是这样的话

     attr_accessible :title, :category_ids
Run Code Online (Sandbox Code Playgroud)

还要确保你真的想要所有表格...如果没有添加这个:

  attr_accessible :title, :category_ids, :as => :admin
Run Code Online (Sandbox Code Playgroud)

然后

@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
Run Code Online (Sandbox Code Playgroud)

要么

@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
Run Code Online (Sandbox Code Playgroud)