渲染js动作并传递本地

时间:2014-08-11 19:40:08

标签: javascript ruby-on-rails

我有一个部分表单,用作follow / unfollow按钮。当我遍历商店列表时,我有一个按钮来关注/取消关注每个商店。

表单提交:remote => true,我希望通过呈现包含该特定商店按钮的更改状态的div进行响应。

def follow_from_index
  @store = Store.find(params[:store_id])
  current_user.vote_for(@store)
  render action: 'toggle_index'
end

我现在将每个包含div的ID设置为商店的AR ID:id="<%= store.id %>"

我希望我可以为toggle_index执行类似的操作:

$("<%= store.id %>").html("<%= escape_javascript render('favorite_index') %>");

我可以从控制器向toggle_index动作传递有问题的商店的局部变量。我该如何做到这一点?或者,是否有更直接的途径来实现这一目标?

更新

这是我的部分内容:

<% if current_user.voted_for?(store) %>
        <%= link_to image_tag("followactive.png"), 
                { :controller => :stores, 
                :action => 'unfollow_from_index', :store_id => store.id},
                { :method => 'delete', :remote => true }%>
<% else %>
        <%= link_to image_tag("follow.png"), 
                { :controller => :stores, 
                :action => 'follow_from_index', :store_id => store.id},
                { :method => 'post', :remote => true} %>
<% end %>

调用渲染部分:

<%= render partial: 'stores/favorite_index', :locals => {:store => s} %>
# while looping through @stores.each do |s|

1 个答案:

答案 0 :(得分:1)

如果我正确理解你,你会希望你的控制器动作呈现javascript。做这样的事情:

def follow_or_unfollow
  @store = Store.find(params[:store_id])

  if current_user.voting_for?(@store)
    current_user.unvote_for(@store)
  else
    current_user.vote_for(@store)
  end

  respond_to |format|
    format.js
  end
end

然后在你的视图中创建一个名为follow_or_unfollow.js的文件并将其粘贴到其中:

$("#<%= @store.id %>").html("<%= escape_javascript( render partial: 'favorite_index', locals: {store: @store} ) %>");

注意jquery开头的“#”,因此它知道这是一个ID。最后确保_favorite_index.html.erb存在于同一目录中的某个位置并呈现新的按钮状态。