2016-06-16 2 views
0

Rails newbie here; 사용자, 기사, 코멘트 - - 그래서 나는 세 가지 클래스가 두 개의 기존 클래스를 참조하는 방법은 무엇입니까?

class User < ActiveRecord::Base 
    has_many :articles 
end 

class Article < ActiveRecord::Base 
    belongs_to :user 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

가 지금은 특정 사용자로 의견을 꿔, 즉 각 주석이 각 기사가 연결되어 얼마나 사용자 (연결됩니다 사용자). has_many 및 belongs_to를 user.rb에 추가하는 것 외에는 어떻게해야합니까? & comment.rb? 나는 나 자신을 분명히하기를 희망한다.

답변

0

UserComment과 유사한 관계를 추가합니다. 따라서 댓글의 길이는 user_id이고 article_id입니다.

class User < ActiveRecord::Base 
    has_many :articles 
    has_many :comments 
end 

class Article < ActiveRecord::Base 
    belongs_to :user 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :user 
end 

당신은 당신의 comments 테이블에 user_id 필드를 추가 모델을 경고 한 후 마이그레이션을 작성해야합니다.

rails g migration AddUserRefToComments user:references 

그런 다음 rake db:migrate을 실행하십시오. 희망이 도움이됩니다.

+0

나는 이미 그렇게 해왔다. 컨트롤러에는 다른 것이 필요하지 않습니다. – Arif

+0

아니요, 컨트롤러에는 아무 것도 없습니다. 그러나 새로운 주석을 작성하는 동안 해당 주석에 현재 사용자의 ID를 저장해야합니다. – Kumar

+0

감사! 아마 두꺼운지만, 현재 사용자의 ID를 주석에 저장하는 데 문제가 있습니다. '@ article.current_user.comments.create (comment_params)'를'CommentController'의'create' 메소드에서 시도합니다,'@article = Article.find (params [: article_id])')하지만 오류는 – Arif

관련 문제