如何定义,在两种不同的方式相互关联的两个模型之间的ActiveRecord的关系?
题
在我的应用我有类用户,视频和投票。用户和视频可以以两种不同的方式彼此相关:作为一个一对多或作为许多一对多。前者是当用户提交视频(一个用户可以提交多部影片)。后者是当用户投票的视频(用户必须通过选票许多影片,反之亦然)。这里是我的代码,它不工作(我想 - 我可能会做一些错误的观点)。请帮我理解正确的方法来组织这些协会:
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
解决方案
class User < ActiveRecord::Base
has_many :videos # Submitted videos
has_many :votes
has_many :voted_videos, :through => :votes # User may vote down a vid, so it's not right to call 'likes'
end
class Vote < ActiveRecord::Base
belongs_to :video
belongs_to :user
end
class Video < ActiveRecord::Base
belongs_to :user
has_many :votes
has_many :voters, :through => :votes
end
的更多细节可以在这里找到: http://guides.rubyonrails.org/association_basics.html
希望它能帮助=)
其他提示
我还没有和检查,但它是这样的:
相反
的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
用于多态关联。请参见。
感谢您的帮助球员,明确指出我在正确的方向。下面是工作的代码:
class User < ActiveRecord::Base
has_many :videos, :as => :submissions
has_many :votes
has_many :likes, :source => :video, :through => :votes
end
class Vote < ActiveRecord::Base
belongs_to :video
belongs_to :user
end
class Video < ActiveRecord::Base
belongs_to :user
has_many :votes
has_many :voters, :source => :user, :through => :votes
end
PS我一直是为:喜欢,因为这个程序,他们将不能够downvote,只是给予好评
不隶属于 StackOverflow