どのように私は2つの異なる方法で相互に関連して二つのモデル間のActiveRecordの関係を定義していますか?
質問
私のアプリでは、私はクラスのユーザー、ビデオ、および投票を持っています。ユーザーとビデオは、2つの異なる方法で相互に関連付けることができます:1対多として、または多対多。ユーザーはビデオを(1人のユーザーが多くのビデオを提出することができます)送信すると、前者があります。後者は、(ユーザーが多くの票を通じてビデオ、およびその逆を持っている)、ビデオのときに、ユーザーの投票です。 ( - 私は、ビューで間違った何かをすることができると思う)ここでは動作しません、私のコードは、です。私はこれらの関連を構造化するための正しい方法を理解する助けてくださいます:
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
このアプリでは、彼らは唯一のupvote、downvoteすることができなくなりますので、好きな:。私のようにそれを守っPS
所属していません StackOverflow