1

我最近开始使用 Rails 3.2,但在尝试在我的应用程序中实现一些 ajax 功能时被卡住了。我完全遵循了这个 railscast (http://railscasts.com/episodes/240-search-sort-paginate-with-ajax)。除此之外,我想为每个产品实现一个候选列表按钮,让用户将产品列入候选列表并将它们存储在会话中。我还希望在同一页面上显示一小部分入围产品,这需要 ajax 更新。

我想知道最好的方法是什么。我目前实现了带有远程标记的 link_to 按钮和一个帮助函数来将链接更改为候选列表/取消候选列表。我还使用条件 div 根据候选名单的长度显示候选名单。但是,问题是每当我入围时,产品表的顺序也会被重置。

这是我的代码片段:-

Application_helper.rb

def shortlist_unshortlist_link(product_id )
  if (user_session.already_shortlisted? product_id )
    link_to 'Unshortlist', { action: 'unshortlist', id: product_id  }, remote => 'true'
  else
    link_to 'Shortlist', { action: 'shortlist', id: product_id  }, remote => 'true'
  end
end


def shortlist_div
  shortlist=user_session.shortlist
   if (user_session.shortlist.length > 0)
     render :partial => 'pages/shortlist_fields'
   end
end

产品/index.html.erb

<div id="product">
 <% @products.each do |product| %>
<tr>....
<td><%= shortlist_unshortlist_link(product.id.to_s) %></td>
</table>
</div>
<div class="shortlist"><%= shortlist_div() %> </div>

products_controller.rb

def shortlist
 user_session.add_to_shortlist(params[:id])
 redirect_to products_path
end

def unshortlist
 user_session.remove_from_shortlist(params[:id])
 redirect_to products_path
end

我认为,问题是由于redirect_to,但我不知道如何在不损害功能的情况下避免这种情况。我在这里走错了路吗?这是实现这一点的好方法吗?有什么建议么。

谢谢,阿米特

4

2 回答 2

0

你应该在候选名单方法中使用,

respond_to do |format|
  format.html {redirect_to products_path }#shortlist.html.erb
  format.js #shortlist.js.erb
 end

并将您的 java 脚本写入 #shortlist.js.erb 文件。

对未入围名单做同样的事情。

于 2012-12-02T16:26:34.637 回答
0

我同意 Sush,您没有响应来自link_to.

在您的控制器中,入围方法,响应 ajax 请求

respond_to do |format|
  format.html {redirect_to products_path }
  format.js 
end

按照 Rails 的约定,format.js将执行与您的方法同名的 js.erb 文件。

在 shortlist.js.erb 中,您可以编写如下内容:

$('#shortlist').html('<%= escape_javascript(render "pages/shortlist_fields")%>');

此外,您还可以调用相同的 js.erb 文件。

在 unshortlist 方法中,您可以这样做:

respond_to do |format|
  format.html {redirect_to products_path }
  format.js {render :action=>'shortlist'}
end
于 2012-12-02T17:19:26.277 回答