2014-01-11 3 views
0

새 일, 새 오류 일 것 같습니다.RoR ActiveRecords 조건 - 테이블의 데이터에 올바르게 액세스하는 방법

"의견"표가 있습니다. 내가 코멘트 @ 인쇄 할 경우 = Comment.all, 나는이 형식으로 내 데이터베이스에서 데이터를 얻을 : 나는 모든 의견 "수신기"= aSpecificName AND "commentable_type"= 서비스를 얻으려면

[#<Comment id: 1, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:11:44", updated_at: "2014-01-10 18:11:44", content: "yolo drake", receiver: nil>, #<Comment id: 2, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:12:20", updated_at: "2014-01-10 18:12:20", content: "yolo drake", receiver: nil>, #<Comment id: 3, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:14:07", updated_at: "2014-01-10 18:14:07", content: "schallulaaa udddaa", receiver: "Linda Lamar">, #<Comment id: 4, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:17:28", updated_at: "2014-01-10 18:17:28", content: "noch ein versuch", receiver: nil>, #<Comment id: 5, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:18:42", updated_at: "2014-01-10 18:18:42", content: "scdcsvcdf", receiver: nil>, #<Comment id: 6, commentable_id: nil, commentable_type: nil, user_id: 1, created_at: "2014-01-10 18:20:05", updated_at: "2014-01-10 18:20:05", content: "luiscdncdij", receiver: "Miriam Hagen">] 

. 내가 comments.each @ 할 경우

하지만

1

은)는 모든 의견을 내게이 제공하는 대신 각 주석 데이터베이스 객체의 각 코멘트를 얻기 위해 수행

#<Comment:0x007f9ec4cbb488> #<Comment:0x007f9ec4cba9c0> #<Comment:0x007f9ec4cb97a0> #<Comment:0x007f9ec4cc2710> #<Comment:0x007f9ec4cc0d48> #<Comment:0x007f9ec4ccbf90> # (the list goes on same style) 

2)

#<ActiveRecord::Relation:0x007f9ec4dd3c80> 
: 나는

@offerpm = Comment.where({ receiver: @user["first_name"], commentable_type: "offer" }), 

뭔가를 할 경우 나에게이 있습니다

===> 여기서 무슨 일이 일어나고 있고 내가 무엇을 선택할지 어떻게 선택합니까?

답변

1

이 시도 :

Comment.where(receiver: 'aSpecificName', commentable_type: 'Offer') 

편집 :

난 당신이 꽤 많이도 자신의 질문에 대답을 참조하십시오! documentation on the ActiveRecord query interface 읽어주십시오

Comment.where({ receiver: @user["first_name"], commentable_type: "offer" }).each do |comment| 
    # do stuff here 
end 

: 관계 오브젝트 당신은 또한에 each 방법을 사용할 수있는 배열과 같은 객체입니다.

+0

아직도 나에게 똑같이 제공됩니다. 그 숫자가 '0x007f9ec4dd3c80'과 같은 것을 어디서 얻었는지 그리고 그 의미는 무엇입니까? – mcn

+1

이것은 Relation 객체에 대한 to_s 메소드의 결과입니다. Relation은 ActiveRecord의 쿼리 빌더의 일부입니다. 'to_a' 또는'each'를 호출 해보십시오. 내가 링크 된 문서를 읽으십시오. 그것은 당신의 모든 질문에 답합니다. – fivedigit

+0

덕분에, 저를 위해 일했습니다! – mcn

1

보고있는 번호가 개체입니다. 이미 무엇을 선택할지, 즉 올바른 개체를 선택하고 있습니다. 이제 그 숫자 대신 원하는 필드를보기 위해 메서드를 호출하면됩니다.

그래서 귀하의 예제에서 해당 필드를보고, 수신기 사용

@offerpm.receiver 

또는 @offerpm.commentable_type를 얻을 수 있습니다.

희망이 있습니다.

관련 문제