我有两个关系 m:n 类型,将表 Users
与表 Videos
链接起来。我通过这些行命令创建它:
rails generate migration users_comments_videos
rails generate migration users_views_videos
我在user.rb和videos.rb文件中分别添加了说明:
has_and_belongs_to_many :users
has_and_belongs_to_many :videos
这两条指令对我创建的两个关系都有效吗?
最佳答案
选择不同的关联名称,然后指定模型。
用户.rb
class User
has_many :comments
has_many :views
has_many :comment_videos, :through => :comments, :source => 'Video'
has_many :view_videos, :through => :views, :source => 'Video'
end
视频.rb
class Video
has_many :comments
has_many :views
has_many :comment_users, :through => :comments, :source => 'User'
has_many :view_users, :through => :views, :source => 'User'
end
关于ruby-on-rails - Ruby on Rails 两个模型之间的多重多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10864590/