开发者

rails if null then else without repeating query for associated table

开发者 https://www.devze.com 2023-01-16 04:06 出处:网络
I have the following code. This code executes the same sql query twice. Because images is an associated table of properties.

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:

  1. url field for the image is null, but an image exists
  2. 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消