我有以下生成最高级列表的代码:
<%= render :partial => 'superlative', :collection => @profile.superlatives %>上面引用的:partial代码如下:
<li class="superlative"><span title="<%= superlative.name %>">
<%= superlative.body %>
</span></li>如何向@profile.superlatives集合添加to_sentence?我试过了:
<%= render :partial => 'superlative', :collection => @profile.superlatives.to_sentence %>但是,这样做会使@profile.superlatives从视图中消失。
我看了文档,但找不到答案。
发布于 2011-09-29 01:24:41
哦,现在我明白了。很抱歉给你造成了混乱。这就是我要做的:
在您的控制器中:
@superlative_bodies = @profile.superlatives.map &:body
# Equivalent to: @superlative_bodies = @profile.superlatives.map {|sup| sup.body }在您的视图中:
= @superlative_bodies.to_sentence有些人会在视图中执行所有这些操作,这取决于您:
= @profile.superlatives.map(&:body).to_sentence要解释一下,.map是一个非常有用的Ruby方法,它接受一个数组或其他可枚举对象和一个块,并返回一个新的数组,其中每个元素都是在块应用到原始数组后的对应元素。例如:
[ 'foo', 'bar', 'baz' ].map {|word| word.upcase } # => [ 'FOO', 'BAR', 'BAZ' ]
# or
[ 'foo', 'bar', 'baz' ].map &:upcase # => [ 'FOO', 'BAR', 'BAZ' ](后者只是前者的简化版本,当您只想在每个元素上调用相同的单个方法时。)
发布于 2011-09-28 13:10:03
也许是这样的吧?
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) %>https://stackoverflow.com/questions/7578233
复制相似问题