我已经建立了用户和轮回之间的多对多关联。我正在试图存储谁是特定旋转的创建者。Rails:在多对多的关联中添加信息
类用户
has_many :rotazations
has_many :rotas, :through => :rotazations
类罗塔岛
has_many :rotazations
has_many :users, :through => :rotazations, :order => 'name ASC'
类Rotazation
belongs_to :user
belongs_to :rota
before_create do |rotazation|
rotazation.creator_id = rotazation.user_id
end
当轮状病毒被创建,我已经成功地在rotazation表中设置了creator_id以具有创建rota的用户的id。我的问题是,我该如何访问:
rota.creator
我尝试
我试图添加以下内容:
罗塔类
用户分类
has_many :created_rotas, :class_name=> "Rota", :through => :rotazations, :foreign_key => "creator_id"
但是,这并不奏效。任何想法如何实现rota.creator工作?谢谢!
非常好的一点。所以它是用户和Rota之间的多对一关系。我通常使用:user.rotas创建轮回。创建 我想知道,我可以在创建rota时自动将创建者字段指向创建它的用户来实现回调吗? – Karan 2012-07-29 13:25:28
由于has_many通过关联,你可以执行'user.rotas.create',否则你必须以用户身份执行并且不能直接连接rota。我认为你最好的选择是在你的表格中加入一个hidden_field。我假设你有一个current_user助手,所以你可以包含'<%f.hidden_field:creator,:value => current_user.id%>'。每创建一个新的rota,'creator'都会存储当前用户的id。 – gabrielhilal 2012-07-29 13:35:28