什么是在belongs_to关联中解决批量分配的正确方法

时间:2013-04-13 20:38:22

标签: ruby-on-rails

假设我有两个模型:

class Article < ActiveRecord::Base
  belongs_to :category
  attr_accessible :content

  validates :content, :category, :presence => true

end

class category < ActiveRecord::Base
  attr_accessible :name
  has_many :articles
end

我正在创建一个表单来添加新文章,并且在此表单中希望为用户提供从列表中选择一个类别的可能性。

= form_for([:admin,@article] , :html => {:multipart => true}) do |f|


  = f.label :category
  = f.collection_select(:category, Category.all, :id, 
       :name,{:prompt => 'select category'}, {:style => 'height:50px;'})

  = f.label :content
  = f.text_area :content, class: 'tinymce', cols:60, rows: 15
  %hr

  = f.submit 'send'

当我提交表单时,我收到错误无法批量分配受保护的属性:类别,我理解。 要解决问题,我将category_id添加到Article的attr_accessible并将表单更改为:

= f.label :category_id
 = f.collection_select(:category_id, Category.all, :id, 
  :name,{:prompt => 'select category'}, {:style => 'height:50px;'})

然后一切正常(我可以在db中创建带有关联category_id的Article对象),但我不认为这是一种正确的方法。 下面是我在ArticlesController中的创建操作

def create
    @article = Article.new(params[:article])
    if @article.save
      redirect_to([:admin,@article])
    else
      render 'new'
    end

  end

有人可以解释我如何改善这一点。

1 个答案:

答案 0 :(得分:1)

如果您不想使属性可分配,则需要使用其名称直接调用它:

def create
  @article = Article.new(params[:article][:content])
  @article.category_id = params[:article][:category_id]
  if @article.save
    redirect_to([:admin,@article])
  else
    render 'new'
  end

end

在这种情况下,质量分配漏洞看起来很小,所以留下它可能没问题。您要避免的是通过发送任意形式的POST来暴露用户可能恶意设置模型属性(例如user.admin标志)的任何属性。

相关问题