2014-11-20 84 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

相关问题