rails if null then else without repeating query for associated table
I have the following code. This code executes the same sql query twice. Because images is an associated table of properties.
Is there a way to do only one query, but still have the same result?
(@property.images.first ? @property.images.first.url : "/img/nophoto.jpg")
Extra clarification: the solution should 开发者_Python百科work in 2 scenario's:
- url field for the image is null, but an image exists
- no image exists for that property
If you want to do it on one line you can do:
(((first_image = @properties.images.first) && first_image.url) ||
"/img/nophoto.jpg")
But it is probably clearer to do the assignment on a separate line:
first_image = @properties.images.first
(first_image && first_image.url) || "/img/nophoto.jpg"
image_url = @property.images.first.url
(image_url ? image_url : "/img/nophoto.jpg")
Even though it has two lines its a simple solution (at least for me :D)
精彩评论