Search code examples
ruby-on-railsparametersfindlink-to

rails: Link_to find-method


How do I use link_to like a database filter in rails?

images --> belong_to: galleries --> Click on gallery --> Opens view of all images of the gallery (Not of all records in database!)

<%= link_to 'Images of Gallery', controller: "images" %>

This is working, but it shows me all available pictures in the database. I need to put something like the next snippet to the link_to:

@gallery = Image.find(params[:gallery_id])

How do I do that?


Solution

  • I dont know why both answers did't work. I got an error "Couldn't find without ID" error.

    This solution did the job:

    I called a before_action method in my controller:

    before_action :set_gallery, only: [:show, :edit, :update, :destroy]
    

    in the set_gallery method I put this:

      def set_gallery
        @gallery = Gallery.find(params[:id])
        @images = @gallery.images
      end
    

    Then I changed the link_to the the basic show action:

    <%= link_to 'Preview', gallery %>
    

    After that I changed the show.html.erb and added an image iteration:

      <% @images.each do |image| %>
      ... <%= image.img_url %> ...
      <% end %>
    

    I will try to find out, why your suggested solutions didnt work. Cant explain it right now.