[英]ruby logic for getting first image of each listing
I have a listing model
. 我有一个listing model
。 Each listing has many
images. 每个列表都有many
图像。 So in my index
page I want to display all listings and the first image of each listing. 因此,在index
页面中,我想显示所有列表以及每个列表的第一张图片。 So in controller I first fetch all listings which has all fields like :name
, :
description, etc
. 因此,在控制器中,我首先获取所有包含诸如:name
, :
description etc
所有字段的列表。 Now for the images part is where am stuck. 现在,对于图像部分是卡住的地方。 How can I properly add the : custom_url
field with the image url
in each room using ruby
code? 如何使用ruby
代码在每个房间的image url
中正确添加: custom_url
字段?
(NB: I am using angular on front end so this is just for the json and dont want to add a seperate field in database for the first image) (注意:我在前端使用了angular,所以这仅用于json,并且不想在数据库中为第一个图像添加单独的字段)
So here is the controller code 所以这是控制器代码
def search
@listings = Listing.all
custom_url = listing.photos[0].image_url(:medium)
respond_to do |format|
format.html
format.json { render json: {listings: @listings} }
end
end
In the Listing model add a method that gets the image url and call it custom_url
在清单模型中,添加一个获取图像URL并将其命名为custom_url
Listing.rb Listing.rb
def custom_url
photos.first.image_url(:medium)
end
Then in the render_json
include the method custom_url
: 然后在render_json
包含方法custom_url
:
def search
@listings = Listing.all
listings_json = @listings.as_json({methods: :custom_url}
respond_to do |format|
format.json { render json: {listings: listings_json }
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.