开发者

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 new开发者_如何学Cest 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜