2012-07-23 4 views
0

나는이 user_profilehas_one 협회 선택 특정 필드

has_one 협회와 내가 user_profile로 대신 user_profile의에서 이름 필드를 선택합니다 user 모델. *

내가 시도

,

user = User.first 
user.user_profile.select(:name) 

하지만 이건 작동하지 않습니다.

+0

나는 레일 3.2을 사용하고를 .5 – shajin

답변

1

업데이트 : 것 같다

, 즉 다른 방향과 다르게 일대일 연결을 처리 레일. 당신은 두 가지 옵션이 있습니다

1) 협회에서 선택한 속성 정의를 항상 선택합니다 그

has_one :user_profile, :select => [:name, :id]

2)처럼, select를 추가 할 수 있습니다 모델의 특정 찾기를 정의 이 :

def my_profile 
    UserProfile.find(self.user_profile_id) 
end 

.... 

my_profile.select(:name) 

ORIGINAL :

has_many 방향의 경우, 작동 :

내가 좋아하는, 내 코드에서 방법을 시도했다 :

= User.find("admin").article.select(:title).to_sql 

그것은 올바른 SQL 반환

SELECT title 
FROM "articles" 
WHERE "articles"."user_id" = 1364 
+0

귀하의 경우에는 사용자가 추측하는 기사와 has_many 관계를 맺고 있습니다. 그리고 mycase에는 has_one과 user_profile을 가진 사용자가 있습니다. – shajin

+0

네, 맞습니다. 업데이트를 참조하십시오. – Matzi