ruby-on-rails – has_many通过其他属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – has_many通过其他属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们如何通过关联在has_many中设置其他参数?

谢谢.
Neelesh

解决方法

这篇博文有完美的解决方案: 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

以前你可能已经走了:product.collaborators<<当前用户. 但是,要设置附加参数(在此示例中为is_admin),而不是自动添加到数组的方式,您可以手动执行以下操作: product.save&& product.collaborators.create(:user => current_user,:is_admin => true)

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

原文链接:https://www.f2er.com/ruby/274293.html

猜你在找的Ruby相关文章