A
A
artem_music2016-04-17 13:39:48
MySQL
artem_music, 2016-04-17 13:39:48

What is the correct way to write WHERE in Rails?

Good afternoon, I apologize in advance if my question seems stupid to you - I'm still new to rails.
There is a Wedding model, to which photos (another model) are attached using the Paperclip gem.
To display, for example, the first photo, I do this:

#в контроллере
@wedding = Wedding.last
#во вьюхе
<%= image_tag @wedding.photos[0].image.url(:medium) %>

There was a problem - if the object does not have a photo, then the application crashes. How to correctly form a query, taking into account the attached model?
Something like Wedding.where(this.photos != nil)
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fahrenhe17, 2016-04-17
@artem_music

=image_tag @wedding.photos[0].image.url(:medium) unless @wedding.photos.empty?

this is if you need all the wedding elements, regardless of the presence of a photo. If you need everything only with a photo, then it is better to make a scope in the model
to the where account along with the attached model -
scope :with_photos, -> { joins(:photos).where('photos.empty? = ?', false) }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question