1

내 앱에는 User, Video 및 Vote 클래스가 있습니다. 사용자와 비디오는 일대 다 (one-to-many) 또는 다 대다 (many-to-many)의 두 가지 방식으로 서로 관련 될 수 있습니다. 전자는 사용자가 비디오를 제출하는 경우입니다 (한 명의 사용자는 많은 비디오를 제출할 수 있음). 후자는 사용자가 동영상에 투표 할 때입니다 (사용자는 투표를 통해 많은 동영상을 보유하고 그 반대의 경우도 마찬가지입니다). 여기 내 코드가 작동하지 않는다 (나는 생각한다 - 내가보기에 뭔가 잘못되어있을 수있다). 날이 협회 구조하는 올바른 방법을 이해 도와주세요 :서로 다른 두 가지 방식으로 서로 관련이있는 두 모델간에 ActiveRecord 관계를 정의하는 방법은 무엇입니까?

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 
+0

작동하지 않는 항목으로 확장 할 수 있습니까? 오류가 있습니까? –

+0

내가하려고 할 때 : video.voters << user, "#Video : 0xb752b270에 대한 정의되지 않은 메서드 'voters'가 나타납니다 –

답변

1
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

은 확실히 올바른 방향으로 절 지적,)은 = 도움이 당신의 도움들에 대한

2

내가 사라 및 확인하지 않은,하지만 그것은 다음과 같이 진행됩니다

대신

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을 참조하십시오.

+0

올바른 방향으로 설정합니다. 누락 된 유일한 것 : source => : user & : source => : video. 그럼 class_name 부분없이 시도해 봤지만 여전히 : source로 작업했습니다. 감사합니다! upvote하지만 충분한 담당자가 없습니다. –

1

감사를 바랍니다. 내가로 유지

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 할 수 없기 때문에 좋아 여기 작업 코드입니다.