2014-11-20 134 views
0

我正處於我的第一個rails項目的中間,並且已經到達想要根據SELECT標記的值更改模型索引的ORDER BY的階段。在jQuery Ajax調用之後Rails視圖不會更新

我在index.html.erb以下的onchange

<div id="sortBy"> 
     <span>Sort by:</span> 
     <%= select_tag "sort_by", options_for_select([ "Newest first", "Oldest first" ], "Newest first"), { :onchange => "changeSortOrderJs(this.value)" } %> 
</div> 

這應該更新這樣的:因爲它

<% @horses.each do | horse | %> 
    <%= horse.name %> 
<% end %> 

這就要求在我的CoffeeScript資產以下方法(前綴爲@是一個匿名函數):

@changeSortOrderJs = (val) -> 
    $.ajax 
    type: 'GET' 
    url: '/horses' 
    data: order: val 

這映射到我的索引行爲在HorsesCont輥

def index 
     order = params[:order] 

     if(order == nil) 
      order = 'Newest first' 
     end 

     @horses = Array.new 

     if order == 'Newest first' 

      @horses = Horse.all.order("created_at DESC") 

     elsif order == 'Oldest first' 

      @horses = Horse.all.order("created_at ASC") 
     end 

     //tried this later but didn't work either 
     respond_to do |format| 
      format.html 
     end 
    end 

我可以在development.log所看到的工作和@horses以正確的順序被填充。但是這個觀點並沒有刷新。

如果我使用respond_with(@horses),然後在Ajax調用成功的回調,即

@changeSortOrderJs = (val) -> 
    $.ajax 
    type: 'GET' 
    url: '/horses' 
    data: order: val 
    success: (result) -> 
     $('body').html(result) 

那麼它的工作和馬匹得到重新排序。但我寧願不以這種方式取代整個身體。

我認爲帶有實例變量的整個觀點是,您可以重新定義它們,視圖會自動更新?

+0

順便說一句,':平變化=> 「changeSortOrderJs(THIS.VALUE)」'是有點老派,你最好用'$('#sortBy select')。change - > ...'。 – 2014-11-20 18:48:03

回答

1

實例變量不會神奇地更新頁面。您必須像使用最後一段代碼一樣使用成功功能。如果你想要立即更新,你應該看看使用Knockout.js或類似的東西

此外,如果你打算渲染partials,你必須在Coffeescript文件外進行。例如,在你的控制器做:

和APP /控制器/馬/ index.js做:

container = $('#your_div_here'); 

<% @horses.each do |horse| %> 
    container.prepend("<%= j render(:partial => 'horses/horse', :locals => { :horse => horse }) %>"); 
<% end %> 
+0

啊,好的。有沒有什麼辦法可以讓回調馬回HTML而不是絕對一切? – tacua 2014-11-20 18:08:39

+1

是的,但是如果你打算渲染一堆部分,你必須在Coffeescript文件之外這樣做,因爲你將無法訪問渲染方法。看到我的編輯答案。 – 2014-11-20 18:12:08

+0

感謝您的編輯。我是否應該考慮讓馬(而不是馬)部分避免多次渲染? – tacua 2014-11-20 18:24:12

相關問題