서로 다른 두 가지 방식으로 서로 관련된 두 모델 간의 ActiveRecord 관계를 어떻게 정의합니까?

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

문제

내 앱에는 수업 사용자, 비디오 및 투표가 있습니다. 사용자와 비디오는 두 가지 방식으로 서로 관련 될 수 있습니다. 일대일 또는 다수의 사람으로서. 전자는 사용자가 비디오를 제출할 때입니다 (한 사용자가 많은 비디오를 제출할 수 있음). 후자는 사용자가 비디오에 투표 할 때입니다 (사용자는 투표를 통해 많은 비디오가 있고 그 반대도 마찬가지). 여기에 제 코드가 작동하지 않습니다 (생각합니다.보기에서 뭔가 잘못하고있을 수 있습니다). 이러한 연관성을 구성하는 올바른 방법을 이해하도록 도와주세요.

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

becomes

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

추신 : 나는 그것을 좋아한다 : 좋아한다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top