Topic: Join table query

Hi,
I'm learning Rails and can't figure out how to query the join table I created...

The join table is "galleries_pictures"  and I am trying to retrieve all pictures from the selected gallery. 

Controller:
@gallery = Gallery.where("minisection_id" => session[:minisection_id]).first
@pictures = Gallery.find(@gallery.id).pictures

View:
<% @pictures.each do |picture| %>
              <%= image_tag picture.image_url %>
                        ...
@gallery does contain the correct gallery, but @pictures returns empty even though there is a picture record in the table.

Thanks

Last edited by dcastellano1 (2013-05-02 14:02:53)

Re: Join table query

If you Galey and Picture have (they should) relations defined as follows:

class Gallery < AR
 has_and_belongs_to_many :pictures
end

then you could get all the pictures once you get a Gallery object:

@gallery = Gallery.where("minisection_id" => session[:minisection_id]).first
@pictures = @galery.pictures

See more details at Rails Guides.

Re: Join table query

Try this:

First in your models should like this:

Gallery Models

has_many :pictures

Picture Models

belongs_to :gallery

please watch for it's own pluralization.

Controller:

@gallery = Gallery.where("minisection_id" => session[:minisection_id]).first
@pictures = @gallery.pictures.all

This 'pictures' is refers to 'has_many :pictures' so make sure that the name was same.

View:

<% @pictures.each do |picture| %>
              <%= image_tag picture.image_url %>
                        ...

Re: Join table query

Wait, that your relation was many_to_many? so one picture could be in many galleries?

dcastellano1 wrote:

Hi,
I'm learning Rails and can't figure out how to query the join table I created...

The join table is "galleries_pictures"  and I am trying to retrieve all pictures from the selected gallery. 

Controller:
@gallery = Gallery.where("minisection_id" => session[:minisection_id]).first
@pictures = Gallery.find(@gallery.id).pictures

View:
<% @pictures.each do |picture| %>
              <%= image_tag picture.image_url %>
                        ...
@gallery does contain the correct gallery, but @pictures returns empty even though there is a picture record in the table.

Thanks