简体   繁体   中英

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?

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.

snapshot is set as a local variable in controller, so the template doesn't see it. Set it as an instance variable:

@snapshot = Snapshot.find(params[:id])

then in the template:

:locals   => {:snapshot => @snapshot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM