has_many通过其他属性 [英] has_many through additional attributes

查看:43
本文介绍了has_many通过其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do we set additional parameters in has_many through associations?

谢谢. 尼莱什(Neelesh)

Thanks. Neelesh

推荐答案

此博客文章提供了完美的解决方案:

This blog post has the perfect solution: http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/

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

That solution is: create your ":through model" manually, rather than through the automated way when you append to its owner's array.

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

Using the example from that blog post. Where your models are:

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

以前您可能已经走了:product.collaborators << current_user.

Previously you may have gone: product.collaborators << current_user.

但是,要设置附加参数(在本示例中为is_admin),而不是自动附加到数组的方式,您可以像下面这样手动进行操作:

However, to set the additional argument (in this example is_admin), rather than the automated way of appending to the array, you can do it manually like:

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

此方法允许您在保存时设置其他参数.注意如果尚未保存模型,则product.save是必需的,否则可以省略.

This approach allows you to set the additional arguments at save-time. NB. the product.save is necessary if the model hasn't yet been saved, otherwise it can be omitted.

这篇关于has_many通过其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆