避免在Rails中的`has_many:through`中进行质量分配

时间:2012-01-08 15:01:11

标签: ruby-on-rails mass-assignment

我有一个has_many :topics, :through => :topification的用户模型。在我的Topification模型中,我有topic_iduser_id

但我不希望user_id被大量分配(以避免一个用户为另一个用户设置主题的情况),所以我将其从attr_accessible :topic_id语句中删除。

但是,如果我为用户创建新主题,我会得到WARNING: Can't mass-assign protected attributes: user_id

处理这种情况的Rails方法是什么?这是为了避免在多对多关系的连接模型中进行质量分配。

更新:这就是我的模型和表单的样子:

class User < ActiveRecord::Base
  has_many :topifications, :dependent => :destroy
  has_many :topics, :through => :topifications, :dependent => :destroy
  attr_accessible :topics_attributes, :topic_ids
  validates_associated :topics
end

class Topic < ActiveRecord::Base
  attr_accessible :title, :description
  has_many :topifications, :dependent => :destroy
  has_many :users, :through => :topifications
end

class Topification < ActiveRecord::Base
  belongs_to :topic
  belongs_to :user
  attr_accessible :topic_id
end

以我的形式

  - Topic.all.each do |topic|
      = check_box_tag "user[topic_ids][]", topic.id,
            @user.topic_ids.include?(topic.id), id: dom_id(topic)
      = label_tag dom_id(topic), topic.title

0 个答案:

没有答案