2017-01-11 4 views
0

나는 다음과 같은 모델을 가지고 :Ruby Associations CollectionProxy에서 특정 필드를 가져 오는 방법은 무엇입니까?

class User < ApplicationRecord 
    has_many :hobbies, dependent: :destroy 
end 

class Hobby < ApplicationRecord 
    belongs_to :user 
end 

내보기 사용자와 취미에 출력하려고했다 :

<table> 
    <tr> 
    <th>User</th> 
    <th>Hobby</th> 
    </tr> 
    <% @users.each do |u| %> 
    <tr> 
    <td><%= u.name %></td> 
    <td><%= u.hobbies %></td> 
    </tr> 
    <% end %> 
</table> 

하지만 다음을 참조 :

User Hobby 
Mad Max <Hobby::ActiveRecord_Associations_CollectionProxy:0x007fa2721ab910> 

그것을 나는 컬렉션을 출력하고있는 것처럼 보이지만 실제 취미 이름을 원합니다. 나는 u.hobbies.first, u.hobbies [: 취미] 등을 시도했다. 나는 http://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html 내부를 들여다 보았지만 새로운 개발자로서 나에게 혼란 스럽다. 누군가가 컬렉션에서 특정 필드를 가져 오는 방법을 말해 줄 수 있습니까? 그리고 거기에 어떤 자료가 나에게 미래에 참조 할 좋은 지침입니까?

답변

1

그래서 이것은 기본적으로 사용자에게 연결되는 취미의 배열입니다. 그래서 각각을 반복하고 나서 원하는 속성을 요청해야합니다. 이 같은 것을보십시오 : 당신은 당신이 이런 일을 시도 할 수 진짜 공상을 얻고 싶은 경우에

<table> 
    <tr> 
    <th>User</th> 
    <th>Hobby</th> 
    </tr> 
    <% @users.each do |user| %> 
    <tr> 
    <td><%= user.name %></td> 
    <td> 
     <% user.hobbies.each do |hobby| %> 
     <%= hobby.attribute_name %>, 
     <% end %> 
    </td> 
    </tr> 
    <% end %> 
</table> 

: 삼항 연산자를 사용

<% user.hobbies.each_with_index do |hobby, index| %> 
    <%= hobby.attribute_name %> 
    <%= (index == user.hobbies.length-1) ? '' : ',' 
<% end %> 

는 기본적으로 말을 단지 취미 경우 쉼표를 넣어 마지막 취미가 아니다