2017-12-08 20 views
2

레일의 반응 구성 요소에서 연결된 모델의 필드를 가져 오는 방법이 있습니까?반응 구성 요소에서 연관된 모델의 필드를 호출 할 수 있습니까?

나는 반응 구성 요소를 통해 매핑 중이며 내가 얻고있는 목록 모델과 관련된 모델의 ID를 포함하여 각 레코드 내의 모든 필드를 가져 오는 목록 모델을 가지고 있습니다. 내가 구체적으로 무엇을 달성하고자하는

예를 들어, 내가 리스팅 모델이 있지만, 나는 그것을 얻고 있지 않다 우리가 레일에서하는 것처럼 관련 ID를 통해 다른 필드를 얻을 수 있습니다

listing.modelNameThatIsAssociated.fieldName 

방법 이걸 달성 할까? 여기

내 코드

컨트롤러

def all 
begin 
    @listings = Listing.all 
rescue => e 
    @listings = [] 
end 
end 

def filter 
@listings = Listing.where(nil) 

filtering_params(params).each do |key, value| 
    @listings = @listings.public_send(key, value) if value.present? 
end 
render json: { listings: @listings }, status: 200 
end 

private 
def filtering_params(params) 
    params[:filters].slice(:bedrooms, :bathrooms, :price, :parking) 
end 

all.html.erb 내 구성 요소를 반응 (listings.js.jsx) 여기

<%= react_component('ListingsPage', listings: @listings) %> 

와의 조각

class ListingsList extends React.Component { 
    constructor(props) { 
     super(props); 
} 

render() { 
    const { listings } = this.props; 

    return (
     <div className='ListingList_container'> 
     <table> 
      <thead> 
      <tr> 
      <td>#</td> 
      <td>Name</td> 
      <td>Address</td> 
      <td>Lat</td> 
      <td>Lng</td> 
      <td>Bedrooms</td> 
      <td>Bathrooms</td> 
      <td>Price</td> 
      <td>Parking</td> 
      <td>Building ID</td> 
      </tr> 
     </thead> 
      <tbody> 
      { 
      listings.map((listing, index) => (
       <tr key={listing.id}> 
       <td>{index + 1}</td> 
       <td>{listing.name}</td> 
       <td>{listing.address}</td> 
       <td>{listing.lat}</td> 
       <td>{listing.lng}</td> 
       <td>{listing.bedrooms}</td> 
       <td>{listing.bathrooms}</td> 
       <td>{this.formatNumber(listing.price)}</td> 
       <td>{listing.parking ? 'Available' : 'None'}</td> 

       // below I want to get building name just like we do in rails 
       // through association 'listing.building.name' but, that 
       // doesn't work 
       <td>{listing.building_id}</td> // this works, I am getting building ID 
       <td>{listing.building.name}</td> // this doesn't work 
       </tr> 
      )) 
      } 
     </tbody> 
     </table> 
    </div> 
); 
} 
} 

나는 모든 단일보기와 도움에 감사드립니다 미리 감사드립니다. 제 질문이 명확하지 않은 경우 알려주십시오.

답변

0
그런 다음, 먼저 연결을로드하여 Listing 모델 has_many :offershas_many :views, 그때 당신이 쓰는 것입니다 경우 JSON 출력 예를 들어

에 추가 as_jsoninclude 옵션을 사용해야합니다

이 :

# In the controller 
@listings = Listing.preload(:offers, :views) 

# In your view 
<%= react_component(
    'ListingsPage', 
    listings: @listings.as_json(include: [:offers, :views]) 
) %> 
+0

고맙습니다. @patkoperwas. 내 문제가 해결되었으므로 변경해야합니다. 제공 대상 : 내 업체가 belongs_to : offer이기 때문에 제안합니다. – Hindreen