我的控制器中有以下代码:
文件: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
JavaScript(jQuery): 文件: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从以下位置调用: 应用程序/视图/照片/ show.html.erb
它似乎不起作用。
我的错误:
渲染照片/ 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'
可能会发生什么想法?
答案 0 :(得分:1)
您正尝试将局部变量传递给部分'snapshot_comments'。但是这两个局部变量,快照和注释未在当前范围中定义(在视图中)。
如果要将变量传递给控制器中的视图,则必须执行以下操作:
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}) %>" );
尝试上面的代码,看看它是否有效。我只是将快照和评论更改为@snapshot和@comments。
答案 1 :(得分:0)
快照在控制器中设置为本地变量,因此模板看不到它。将其设置为实例变量:
@snapshot = Snapshot.find(params[:id])
然后在模板中:
:locals => {:snapshot => @snapshot