has_many通过其他属性

Nee*_*esh 12 ruby-on-rails has-many-through ruby-on-rails-3

我们如何通过关联在has_many中设置其他参数?

谢谢.Neelesh

Wil*_*iss 12

这篇博文有完美的解决方案:http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/

该解决方案是:手动创建":through model",而不是在附加到其所有者的数组时通过自动方式创建.

使用该博客文章中的示例.您的模型在哪里:

class Product < ActiveRecord::Base
  has_many :collaborators
  has_many :users, :through => :collaborators
end

class User < ActiveRecord::Base
  has_many :collaborators
  has_many :products, :through => :collaborators
end

class Collaborator < ActiveRecord::Base
  belongs_to :product
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

以前你可能已经离开了:product.collaborators << current_user.

但是,要设置附加参数(在此示例中is_admin),而不是自动添加到数组的方式,您可以手动执行以下操作:

product.save && product.collaborators.create(:user => current_user, :is_admin => true)

此方法允许您在保存时设置其他参数.NB.product.save如果尚未保存模型,则必须使用,否则可以省略.


Uni*_*key 2

has_many :tags, :through => :post_tags, :conditions => ['tag.owner_id = ?' @owner.id]
Run Code Online (Sandbox Code Playgroud)

  • 当标签 &lt;&lt; new_tag 时怎么样? (4认同)