开发者

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 开发者_StackOverflow

$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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜