どのように私は2つの異なる方法で相互に関連して二つのモデル間のActiveRecordの関係を定義していますか?

StackOverflow https://stackoverflow.com/questions/1523541

質問

私のアプリでは、私はクラスのユーザー、ビデオ、および投票を持っています。ユーザーとビデオは、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

タグ)、それは=を役に立てば幸い

他のヒント

あなたの助けの人たちのための

おかげで、間違いなく正しい方向に私を指摘しました。ここでは作業コードがあります:

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top