views:

24

answers:

2

Hi, 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 work in 2 scenario's:

  1. url field for the image is null, but an image exists
  2. no image exists for that property
+4  A: 

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"
Shadwell
I get the following error: undefined method `url' for nil:NilClass
PlanetMaster
it is a case where the property does not have any pictures. So no record exists where 'images.property_id = property.id'. I guess your solution would work if a record in images exists, but where the url field would be null.
PlanetMaster
Is your question right then? Should both references to `@property.images.first` have `.url` called on them. I don't see why you'd get the error with my version and not with yours as it stands.
Shadwell
yes, you are right, I simplified my version a bit in this post. Just corrected it.
PlanetMaster
Okay, I've updated my answer to remove the, now incorrect, response to the original question.
Shadwell
A: 

hi PlanetMaster

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)

cheers sameera

sameera207