2011-03-31 63 views
2
提交局部

我在我的控制器以下代碼:滑軌誤差通過Javascript

文件:應用程序/控制器/ 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的): 文件:應用/視圖/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' 

任何想法可以怎麼回事?

回答

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

+0

已經錯過了意見位;) – oliverbarnes 2011-04-01 02:58:24

+0

我發誓,當我剛剛看到一匹馬的動畫與氣球上投票你的答案。必須是水中的東西... – oliverbarnes 2011-04-01 02:59:28

+0

o親愛的,是因爲愚人節=) – Shanison 2011-04-01 04:01:59

0

快照設置爲控制器中的局部變量,所以該模板沒有看到它。然後

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

模板:將其設置爲一個實例變量

:locals => {:snapshot => @snapshot