Search code examples
javascriptjqueryruby-on-railsrjs

Rails Error submitting partial via Javascript


I have the following code in my controller:

File: app/controllers/photos_controller.rb

def show_snapshot_comments
    snapshot = Snapshot.find(params[:id])
    @photo = snapshot.photo
    comments = snapshot.comments.paginate :page => params[:page]
    @snapshot_comment = snapshot.comments.new
      respond_to do |format|
        format.js
      end
   end

The JavaScript (jQuery): File: app/views/photos/show_snapshot_comments.js.erb

$j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
        :locals   => {:snapshot => snapshot, :comments => comments}) %>" );

show_snapshot_copmments is called from: app/views/photos/show.html.erb

It doesn't appear to be working.

My error:

Rendering photos/show_snapshot_comments

ActionView::TemplateError (undefined local variable or method `snapshot' for #<ActionView::Base:0x2aaaaea473c8>) on line #2 of app/views/photos/show_snapshot_comments.js.erb:
1: $j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
2:         :locals   => {:snapshot => snapshot, :comments => comments}) %>" );

    app/views/photos/show_snapshot_comments.js.erb:2
    app/controllers/photos_controller.rb:227:in `show_snapshot_comments'

Any ideas what may be going on?


Solution

  • You are trying to pass the local variables to the partial 'snapshot_comments". However this two local variables, snapshot and comments are not defined in current scope (in the view).

    If you want to pass variables to views from controller you have to do the following:

    def show_snapshot_comments
        @snapshot = Snapshot.find(params[:id])
        @photo = snapshot.photo
        @comments = snapshot.comments.paginate :page => params[:page]
        @snapshot_comment = snapshot.comments.new
          respond_to do |format|
            format.js
          end
       end
    
    $j('#info').append("<%= escape_javascript(render :partial  => "snapshot_comments",
            :locals   => {:snapshot => @snapshot, :comments => @comments}) %>" );
    

    Try the code above and see if it works. I just change the snapshot and comments to @snapshot and @comments.