Rails 4 - displaying dependent model in a table

I have an article model, with a Photocup dependent model. Each Photocup instance has an image attached (using paperclip / imagemagick). I followed the guide guides for adding a second model, just like the Comments linked to the Article.

http://guides.rubyonrails.org/getting_started.html#adding-a-second-model

It works great. But I want more control over how the Photocups are displayed. I created a partial _gallery.html.erb in Views / Article. The partial gallery looks like this:

  Photo Gallery
 <table class="table2">
 <%= render @article.photocups %>
 </table>

      

_photocup.html.erb in Views / Photocup looks like this:

 <td>
 <%= photocup.label %>
 <br> 
 <%= image_tag photocup.image(:small) %>
 <br>
  <%= link_to 'Remove Photo', [photocup.article, photocup],
           method: :delete,
           data: { confirm: 'Are you sure?' } %>
 </td>

      

Works well, but I can't figure out how to add the line!

Anyway, in order to render Photocups for an article, I am looking at how it is done with an independent model? For example, an index page would usually have something like this

 <table>
 <tr>
 <th>Title</th>
 </tr>
 <%= @photocups.each do |photocup| %>
 </tr>
 <td><%= photocup.title %></td>
 <% end %> 
 </table>

      

Is it possible to do this in the show.html.erb page for the article? Can this be done if I have created a partial in Views / Photocup?

If it matters, the route looks like this:

 resources :articles do
 resources :comments
 resources :photocups
 get 'gallery' 
 get 'showall'
 get 'feature', on: :collection
 end 

      

Thanks in advance for any help.

0


source to share


1 answer


It may be on the page articles#show

. If your associations are correct, you have:

#article.rb
Class Article > ActiveRecord::Base
has_many :photocups
end 

      

and

#photocup.rb
Class Photocup > ActiveRecord::Base
belongs_to :article 
end

      

You will need to declare an instance variable under the show action in the Articles controller. It will look something like this:

#articles_controller.rb
def show
         @article=Article.find(params[:id])
         @photocups=@article.photocups
    end

      



Then use the code for your example index view in your show view and it should show the lines you are looking for.

Also, notice this line:

<%= @photocups.each do |photocup| %>

      

no example is required in your index page =

. The ones that should be reserved for things you want the user to see in the view should be:

<% @photocups.each do |photocup| %>.

      

+2


source







All Articles