2010-12-13 3 views
7

기사와 관련된 댓글을 저장할 모델을 만들고 싶습니다. 앞으로도 앱의 다른 객체에 대한 의견을 원한다는 강한 느낌을 가지고 있습니다. 새 부모 개체를 추가하는 것과 호환 될 수 있도록 내 앱에서 주석 달기를 어떻게 디자인합니까? 나는 여러 컨트롤러/모델을 각 객체에 대한 코멘트 관계를 갖는 시나리오를 피하고자합니다.레일 3에 여러 개의 상위 리소스가있는 중첩 리소스

Nested Resource에서 Ryan Bates 스크린 캐스트를 시청 한 후 단일 부모 아래에서 tp를 자원에 중첩시키는 방법에 대한 확고한 이해를했습니다. 2 개 이상의 상위 리소스에서 어떻게 이것을 수행합니까?

감사합니다.

당신은 Polymorphic Associations을 사용할 수 있습니다 질문의 일부 "새로운 부모 개체를 추가로 앞으로 호환"를

+0

+100 중첩 된 자원에 대해 "회사 파악"이있는 경우 – Zabba

답변

5

. 여기에 nice example이 있습니다. 또한 RailsCast #154을 참조하십시오.

당신을 위해 같이 수있는 방법의 예 :

id:integer 
commentable_type:string 
commentable_id:integer 
comment_text:string 

일부 샘플 기록 :

1,'Article',12,'My first comment' #comment on an Article model 
2,'Question',12,'My first comment' #comment on a Question model 
3,'Question',15,'My first comment' #comment on a Question model 
0

는 답변을

comments 테이블 열 '과 같이 될 수있다 경로에 관한 부분과 자원 찾기.

일반적인 레일 컨트롤러는 부모로부터 하위 리소스를 찾습니다.

GET /articles/{parent_id}/comments/{id} 

GET /articles/0/comments/1 

article = articles.find(parent_id = 0) 
comment = article.comments.find(id = 1) 

다형성 부모와 함께 할 수 없습니다. 자녀에게서 부모를 찾아야합니다.

GET /article/{parent_id}/comments/{id} 
GET /questions/{parent_id}/comments/{id} 

GET /article/0/comments/1 
GET /questions/0/comments/1 

parent = comments.select(parent_id = 0).parent 
comment = parent.comments.find(id = 1) 

라우트를 컨트롤러에 전달할 수 있습니다.

GET /{parent_type}/{parent_id}/comments/{id} 

GET /article/0/comments/1 
GET /questions/0/comments/1 

parent = parent_type.find(parent_id = 0) 
comment = parent.comments.find(id = 1) 

(나는이 방법을 시도하지 않은 한,이 분명히 의사입니다.)

편집 ...

난 당신이 또한 단지 부모의 각 유형에 대해 하나 개의 매개 변수를 추가 할 수도있을 것 같군요.

GET /article/{article_id}/comments/{id} 
GET /questions/{question_id}/comments/{id} 

GET /article/0/comments/1 
GET /questions/0/comments/1 

if article_id 
    article = articles.find(article_id = 0) 
    comment = article.comments.find(id = 1) 

if question_id 
    question = questions.find(question_id = 0) 
    comment = question.comments.find(id = 1) 
관련 문제