在我的应用程序中,我有类用户、视频和投票。用户和视频可以通过两种不同的方式相互关联:一对多或多对多。前者是用户提交视频(一个用户可以提交多个视频)。后者是用户对视频进行投票(用户通过投票拥有多个视频,反之亦然)。这是我的代码,它不起作用(我想——我可能在 View 中做错了什么)。请帮助我了解构建这些关联的正确方法:
class User < ActiveRecord::Base
has_many :videos, :as => :submissions
has_many :votes #have tried it without this
has_many :videos, :as => :likes, :through => :votes
end
class Vote < ActiveRecord::Base
belongs_to :video
belongs_to :user
end
class Video < ActiveRecord::Base
belongs_to :user
has_many :votes #have tried it without this . . . superfluous?
has_many :users, :as => :voters, :through => :votes
end
最佳答案
我还没有去检查过,但它是这样的:
代替
has_many :videos, :as => :likes, :through => :votes
使用
has_many :likes, :class_name => "Video", :through => :votes
与底部相同:
has_many :users, :as => :voters, :through => :votes
成为
has_many :voters, :class_name => "User", :through => :votes
:as
用于多态关联。参见 this chapter in docs了解更多信息。
关于ruby-on-rails - 如何定义以两种不同方式相互关联的两个模型之间的 ActiveRecord 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1523541/