有没有办法从rails中的react组件中的关联模型中获取字段?
我有一个列表模型,我在反应组件中编写并获取每个记录中的所有字段,包括与我获得的列表模型关联的模型的ID。
我特别想要实现的是通过列表模型中的相关ID获取另一个字段,但是,我没有像在rails中那样得到它,例如
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
<%= react_component('ListingsPage', listings: @listings) %>
这里我的反应组件(listings.js.jsx)
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 :(得分:0)
您必须先加载关联,然后使用include
中的as_json
选项将它们添加到JSON输出
例如,如果您的Listing
型号has_many :offers
和has_many :views
,那么您可以写下:
# In the controller
@listings = Listing.preload(:offers, :views)
# In your view
<%= react_component(
'ListingsPage',
listings: @listings.as_json(include: [:offers, :views])
) %>