开发者

How to use to_sentence with an AR collection

开发者 https://www.devze.com 2023-04-07 18:51 出处:网络
I have User.all, which returns 3 results. How can I make it so I can render each result to something like:

I have User.all, which returns 3 results.

How can I make it so I can render each result to something like:

<a href="path_to_user_foo_here">Foo</a>, <a href="path_to_user_bar_here">Bar</a开发者_JAVA技巧>, and <a href="path_to_user_foobar_here">Foobar</a>

Which when rendered in the browser, will display as:

Foo, Bar, and Foobar

I know about the to_sentence helper. But not very sure how to execute this, since User.all returns 3 hash objects. I can use .map(&:first_name), but how will I be able to provide the route path in the link_to method.

Looking for an approach that works.


I think you're looking for something like this. (answer updated)

In a helper:

module ApplicationHelper
  ...
  include ActionController::UrlWriter
  def generate_user_links_sentence
    links = User.all.collect do |user|
      link_to user.first_name, user_path(user)
    end
    links.to_sentence
  end
  ...
end

# Example: <%= generate_user_links_sentence %>

You can separate out the generation logic into your controller if you so wish, but it's difficult enough accessing route paths from a helper, let alone the controller. There may be a better way to do this in a view, but this is all I can really think of right now.

Update: Just in a view:

<%= User.all.collect{|u| link_to u.first_name, user_path(u)}.to_sentence %>
0

精彩评论

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