【问题标题】:How do I define ActiveRecord relationships between two models that relate to each other in two different ways?如何定义以两种不同方式相互关联的两个模型之间的 ActiveRecord 关系?
【发布时间】:2009-10-06 04:03:21
【问题描述】:

在我的应用中,我有 User、Video 和 Vote 类。用户和视频可以通过两种不同的方式相互关联:一对多或多对多。前者是用户提交视频时(一个用户可以提交多个视频)。后者是当用户对视频进行投票时(用户通过投票拥有许多视频,反之亦然)。这是我的代码,它不起作用(我认为 - 我可能在视图中做错了什么)。请帮助我理解构建这些关联的正确方法:

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

【问题讨论】:

  • 你能详细说明什么不起作用吗?是否有错误等?
  • 当我尝试这样做时:video.voters 的未定义方法'voters'

标签: ruby-on-rails ruby activerecord polymorphic-associations has-many-through


【解决方案1】:

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

代替

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 了解更多信息。

【讨论】:

  • 这让我朝着正确的方向前进。唯一缺少的是您还必须添加 :source => :user & :source => :video。然后我在没有 :class_name 部分的情况下尝试了它,它仍然只使用 :source。谢谢!我会投票,但我没有足够的代表
【解决方案2】:
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

希望对你有帮助 =)

【讨论】:

    【解决方案3】:

    感谢你们的帮助,绝对为我指明了正确的方向。这是工作代码:

    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 我将其保留为 :likes,因为在此应用中他们无法投反对票,只能投赞成票。

    【讨论】:

      猜你喜欢
      • 2015-02-05
      • 1970-01-01
      • 2018-07-11
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多