0

So I was wondering how to work with the link_to method and ajax in Rails 3, when redering different partials.

Example:

Let say I have two link in show.html.erb and every link have a partial to render.

<li><%= link_to "Group1", user_path(@user), { :action => 'group1' , :method => :get, :remote => true} %></li>
<li><%= link_to "Group2", user_path(@user), { :action => 'group2' , :method => :get, :remote => true} %></li>

And we are going to render the partials in this div:

<div id="profile-data">
 ...render here...
</div>

In the UsersController we have our call methods for each partial:

def group1
  respond_to do |format|
    format.js
  end
end
def group2
  respond_to do |format|
    format.js
  end
end

And of course we have our js files in the view user folder:

group1.js.erb

$("#profile-data").html("<%= escape_javascript(render(:partial => 'group1')) %>");

group2.js.erb

$("#profile-data").html("<%= escape_javascript(render(:partial => 'group2')) %>");

So my question is: is this the right way to render different partials with ajax? Are I missing something? Do have to route them some way?

This code dosent work right now and I dont know why, any help would be appreciated.

4

2 回答 2

0

link_to 应该有点像

<%= link_to "Group1", {group1_users_path, :format => :js} , :method => :get, :remote => true  %>

或者

<%= link_to "Group1", {:controller=>:users,:action=>:group1, :format => :js} , :method => :get, :remote => true  %>

或者如果它是成员路由并且需要 user_id

<%= link_to "Group1", {group1_users_path(@user) :format => :js} , :method => :get, :remote => true  %>

link_to 的第二个参数是 url 选项,因此只有与 url 相关的选项在其中,其他的应该不在散列中,否则它们将作为参数传递。

在 rails cocs 查看更多详细信息,他们有一些简洁的文档和示例

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

您需要在路由文件中有 group1 和 group2

它应该像

resourses :users do
  collection do 
    get "group1"
    get "group2"
  end
end

这将添加助手 group1_user_path 和 group2_user_path

我建议您彻底阅读 Rails 文档

http://guides.rubyonrails.org/routing.html#adding-more-restful-actions

于 2012-07-27T21:49:57.760 回答
0

您需要在您的 link_to 中明确声明您要发出 javascript 请求。这可以通过将选项哈希中的格式设置为 js 来完成::format => :js.

因此,在您的情况下,它应该如下所示:

<li><%= link_to "Group1", user_path(@user), { :action => 'group1' , :method => :get, :remote => true, :format => :js} %></li>
<li><%= link_to "Group2", user_path(@user), { :action => 'group2' , :method => :get, :remote => true, :format => :js} %></li>
于 2012-07-27T20:52:16.900 回答