开发者

How to add to_sentence to a :collection

开发者 https://www.devze.com 2023-04-09 02:47 出处:网络
I have the following code that generates a list of superlatives: <%= render :partial => \'superlative\', :collection => @profile.superlatives %>

I have the following code that generates a list of superlatives:

<%= render :partial => 'superlative', :collection => @profile.superlatives %>

The :partial code referenced above is as follows:

<li class="sup开发者_运维知识库erlative"><span title="<%= superlative.name %>">
  <%= superlative.body %>
</span></li>

How can I add to_sentence to the @profile.superlatives collection? I tried:

<%= render :partial => 'superlative', :collection => @profile.superlatives.to_sentence %>

Doing so however makes the @profile.superlatives disappear from the view.

I looked at the docs but couldn't find an answer.


Ohhh, now I understand. Sorry for the confusion. Here's what I would do:

In your controller:

@superlative_bodies = @profile.superlatives.map &:body
# Equivalent to: @superlative_bodies = @profile.superlatives.map {|sup| sup.body }

In your view:

= @superlative_bodies.to_sentence

Some people would do this all in the view instead, which is up to you:

= @profile.superlatives.map(&:body).to_sentence

To explain, .map is a super-useful Ruby method that takes an array or other Enumerable and a block and returns a new array where each element is the corresponding element from the original array after the block has been applied to it. For example:

[ 'foo', 'bar', 'baz' ].map {|word| word.upcase } # => [ 'FOO', 'BAR', 'BAZ' ]
# or
[ 'foo', 'bar', 'baz' ].map &:upcase              # => [ 'FOO', 'BAR', 'BAZ' ]

(The latter is just a shortened version of the former for when you only want to call the same single method on every element.)


Something like this, perhaps?

module ProfilesHelper
  # ...
  def superlatives_items (profile)
    @@acb ||= ActionController::Base.new # required to access render_to_string
    profile.superlatives.collect |superlative|
      acb.render_to_string :partial => 'path/to/partial/superlative',
                           :layout => false,
                           :locals => { :superlative => superlative }
    end
  end
  # ...
end

# In view:

# <%= raw(superlatives_items(@profile).to_sentence) %>
0

精彩评论

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

关注公众号