1

在我的应用程序中,我有类User,Video和Vote。用户和视频可以通过两种不同的方式相互关联:一对多或多对多。前者是用户提交视频时(一个用户可以提交很多视频)。后者是用户在视频上投票时(用户通过投票有很多视频,反之亦然)。这是我的代码,它不起作用(我想 - 我可能在视图中做错了事)。请帮我理解正确的方法来组织这些协会:如何以两种不同的方式定义两个彼此相关的模型之间的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 
+0

你能扩展什么不行吗?是否有错误等? – 2009-10-06 04:28:23

+0

当我尝试做:video.voters <<用户,它说:“未定义的方法'选民'为#<视频:0xb752b270> – 2009-10-06 04:43:49

回答

1
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

希望它可以帮助=)

2

我还没有和检查,但它是这样的:

而不是

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

+0

这使我在正确的方向。唯一缺少的是你还必须添加:源=>:user&:source =>:video。然后我在没有:class_name部分的情况下尝试了它,它仍然可以用:source。谢谢!我会upvote,但我没有足够的代表 – 2009-10-06 05:18:05

1

感谢您的帮助球员,明确指出我在正确的方向。这里是工作代码:

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,只是给予好评。

相关问题