簡體   English   中英

如何以兩種不同的方式定義兩個相互關聯的模型之間的ActiveRecord關系?

[英]How do I define ActiveRecord relationships between two models that relate to each other in two different ways?

在我的應用程序中,我有類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

我沒有去檢查,但它是這樣的:

代替

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 # 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

希望它有幫助=)

謝謝你們的幫助,絕對指出了我正確的方向。 這是工作代碼:

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我把它保持為:喜歡因為在這個應用程序中他們將無法進行投票,只能投票。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM