Lee
Lee

Reputation: 661

Using link_to with an instance variable and arguments

I am trying to render a comments partial to use with both the blog and video models. Here's the blog show page asking for the comments partial and passing @blog as the model (I will pass @video on the video's show page):

<%= render :partial => 'comments/comments', :locals => {:model => @blog} %>

This next code is to order the comments as newest first/oldest first:

<% if @comments.count > 1 %>
  <span class="list_order">
    <%= link_to('Newest First', model, :order => "DESC", :anchor => "comments") + " | " +
      link_to('Oldest First', model, :order => "ASC", :anchor => "comments") %>
  </span>
<% end -%>

This works fine when I say:

link_to('Newest First', blog_path(@blog, :order => "DESC".... etc.)

But I know that you can also just pass:

link_to('Newest First', @blog)

and it will automatically go to the blog show page. So in my code, I'm passing the "model" local, and it does refresh the page, but it does not take my argument for :order or :anchor. How do you pass arguments when using only the instance variable rather than the path on the link_to method?

Upvotes: 2

Views: 1947

Answers (1)

Lee
Lee

Reputation: 661

Ok, I finally got the chance to ask a friend of mine and found the solution. I needed to use polymorphic paths. So in my example above, the following code works:

<%= link_to('Newest First', polymorphic_path(model, :order => "DESC", :anchor => "comments") + " | " + link_to('Oldest First', polymorphic_path(model, :order => "ASC", :anchor => "comments") %> 

Then it knows to generate the right path for the variable used. Here's some info on that: http://apidock.com/rails/ActionDispatch/Routing/PolymorphicRoutes/polymorphic_path

Upvotes: 1

Related Questions