1

I have a rails app which displays images of various album covers using an Album model. I want to render a partial view alongside these album covers with the details of a selected album when it is clicked on.

I've looked for examples of this but don't seem to be able to find one that helps me. Having said that I'm new to rails so don't know for sure if I'm looking up the correct terms.

I know this must be a simple question but if anyone can point me in the right direction it would be much appreciated.

UPDATE This seems similar to what I'm looking to do I think:

How to get Rails 3 link_to :partial to work

I've setup my code as follows:

routes.rb

Rails.application.routes.draw do
  root 'albums#index'
  resources :albums do
    get :details, :on => :member
  end

albums_controller.rb

class AlbumsController < ApplicationController
  def index
    @albums = Album.all
  end

  def show
    @album = Album.find(params[:id])
    @tracks = @album.tracks
  end

  def details
    respond_to do |format|
      format.js { render :layout => false }
    end
  end

end

views/albums/index.html.erb

<div class="row">  
  <% @albums.each do |album| %>
  <div class="col-md-3">
    <%= link_to 'Details', details_album_path(:id => album.id),  :remote => true %>
      <div class="thumbnail">
        <img src="<%= album.cover %>">
      </div>
    <% end %>
  </div>
  <% end %>
</div>

<div id="details">

</div>

views/albums/details.js.erb

$( "#details" ).html( "<%= escape_javascript( render( :partial => "details", :locals => { :album => @album} ) ) %>" );

views/albums/_details.html.erb

<div>
  <%= album.title %>
</div>

If I run this and click on the details link for an album I get this error in dev tools:

GET http://localhost:3000/albums/1/details 500 (Internal Server Error)

Rails error message at url shown in dev tools error above

And no partial is shown anywhere.

Very new to rails so any pointers appreciated. If this isn't the best way to go about this then any suggestions welcome.

Community
  • 1
  • 1
Gavin
  • 971
  • 6
  • 10

1 Answers1

0

So I fixed this using Muhammad's suggestion in the comments by updating def details in the albums_controller.rb to include @album = Album.find(params[:id]) :

  def details
    @album = Album.find(params[:id])
    respond_to do |format|
      format.js { render :layout => false }
    end
  end
Gavin
  • 971
  • 6
  • 10