【问题标题】:Can't mass-assign protected attributes: category_ids无法批量分配受保护的属性:category_ids
【发布时间】:2012-07-15 16:37:59
【问题描述】:

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

但是我有这个错误: 无法批量分配受保护的属性:category_ids。 app/controllers/articles_controller.rb:36:in `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 %>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations nested-forms simple-form


    【解决方案1】:

    你在 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
    

    【讨论】:

    • 您好,谢谢!就是这样,我有 attr_accessible :category_id 而不是 :category_ids
    【解决方案2】:

    创建的表单域
    <%= f.association :categories %>
    

    将设置属性category_id,但该属性受到保护。在您的模型中,您应该有一行代码如下所示:

    attr_accessible :title, :teaser, :body, :published
    

    这些属性允许批量分配。如果您希望表单设置category_id,您必须将这些属性添加到attr_accessible 方法:

    attr_accessible :title, :teaser, :body, :published, :category_id
    

    这应该可以解决您的问题。

    【讨论】:

    • 您好,保罗,感谢您的回复。是的,我有这条线,正如 drhenner 指出的那样,问题出在 attr_accessible 中,而不是 :category_id 应该是 :category_ids
    猜你喜欢
    • 2011-09-04
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多