How to get Rails 3 link_to :partial to work

2019-08-03 07:56发布

问题:

In my Rails app I want to have links in a user's Profile that link_to a :partial so that certain parts of the Profile aren't always loaded. I've looked at various articles and questions (mainly this one) but I can't get my link_to working. I currently get a routing error when I load Profiles#Show.

Below is my code. I'm a beginner so if anyone can help me figure out what's going on I'd appreciate it.

<div id="tabs">
  <ul id="infoContainer">
    <li><%= link_to "Link 1", {:partial => 'a'}, {:class => "a"}, :remote => true %></li>
    <li><%= link_to "Link 2", {:partial => 'b'}, {:class => "a"}, :remote => true %></li>
    <li><%= link_to "Link 3", profile_profile_c_path(:id => @user.id), :remote => true %></li>
  </ul>
  <div id="tabs-1">
    # I want to load the partials in this div
  </div>
</div><!-- end tabs -->

I'm using the last link_to as an example:

<li><%= link_to "Link 3", profile_profile_c_path(:id => @user.id), :remote => true %></li>

Here is my `routes.rb file:

match "/profiles/:id/c" => "profiles#profile_c"
resources :profiles do
  get :profile_c
end

Here is the profile_c action in profiles_controller.rb:

def profile_c
  respond_to do |format|
    format.js { render :layout => false }
  end
end

Here is my profile_c.js.erb file:

$( "#tabs" ).html( "<%= escape_javascript( render (:partial => "c", :locals => { :id => @user.id } ) ) %>" );

Here is my _c.html.erb partial:

<% for object in @user.objects %>
<div>
</div>
<% end %>

The error shows No route matches {:action=>"profile_c", :controller=>"profiles", :id=>1}

UPDATE: I no longer get an error. I changed my routes.rb to:

resources :profiles do
  get :profile_c, :on => :member
end

And my link_to to:

<li><%= link_to "Link 3", profile_c_profile_path(:id => @profile.id), :remote => true %></li>

回答1:

make your route like :

resources :profiles do
  get :profile_c, :on => :member
end