加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:54:45 所属栏目:百科 来源:网络整理
导读:我们如何通过关联在has_many中设置其他参数? 谢谢. Neelesh 解决方法 这篇博文有完美的解决方案: http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/ 该解决方案是:手动创建“:through
我们如何通过关联在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.如果尚未保存模型,则必须使用product.save,否则可以省略.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读