2013-09-01 1 views
1

에서 사용자 이름을 액세스. 나는 Message.first하고 내 콘솔에서 시도 : 나는 Message.first.users 할 경우나는 다음 내 모델에서 관계가 다른 모델

Message.first Message Load (0.3ms) SELECT "messages".* FROM 
"messages" ORDER BY "messages"."id" ASC LIMIT 1 => #<Message id: 1, 
subject: "some subject", body: "and some body", created_at: 
"2013-09-01 13:09 :57", updated_at: "2013-09-01 13:09:57", user_id: 1, 
recipient_id: 2> 

, 내가 얻을 :

Message.first.users Message Load (0.3ms) SELECT "messages".* FROM 
"messages" ORDER BY "messages"."id" ASC LIMIT 1 => nil 

나는 기본적으로 recipient_id에서 username를 얻을 싶어요. 이 문제를 잘못 설정 했습니까? 조인 등을해야하나요?

답변

3

belongs_toMessage 모델의 연결 선언이 잘못되었습니다. 자세한 내용은 "The belongs_to Association"을 참조하십시오.

그래서,이 문제가 해결됩니다 당신의 Message 모델을 업데이트 :

class Message < ActiveRecord::Base 
    # use singular :user and :tutor here 

    belongs_to :user 
    belongs_to :tutor 
end 

는 그런 다음 사용하여 메시지의 사용자를 조회 할 것이다 :이 Message.first.user 작동

Message.first.user 
+0

확인을. 그러나, 나는 (가난하게) 설명했듯이 다른 사용자 인'recipient_id'에서 사용자 이름을 얻으려고합니다. 이런 잘못된 일을하고있다 :'User.find (Message.first.recipient_id, select : 'first_name, last_name')'? – DaniG2k

+0

그래서이게 끔찍한 것 같아.하지만 이건 내가 말하고있는 것 같아. User.find (Tutor.find (Message.first.recipient_id)) – DaniG2k

+0

사실 제대로 작동하지 않는 것 같아. 그러나 이것은 :'Tutor.find (message.recipient_id) .user' .... .... 와우, 그건 엉망이야. – DaniG2k

관련 문제