我想创建由许多用户编辑的列表。所以我和许多这样的关系一起去。
class User < ActiveRecord::Base
has_many :editabilities, :dependent => :destroy
has_many :editable_lists, :through => :editabilities, :source => :list
end
class List < ActiveRecord::Base
has_many :editabilities, :dependent => :destroy
has_many :editors, :through => :editabilities, :source => :user
end
class Editability < ActiveRecord::Base
belongs_to :list
belongs_to :user
end
我为这个列表添加了一个编辑器。
u = User.first
l = List.first
Editability.create(user_id: u.id, list_id: l.id)
似乎工作正常。但我不确定我是以正确的方式还是以错误的方式做事。这是正确的做法吗?
答案 0 :(得分:1)
此外:
u = User.first
l = List.first
u.editable_lists << l
http://guides.rubyonrails.org/association_basics.html#has-many-association-reference