Rails 3 重构问题
以下视图代码生成一系列带有总计的链接(如预期):
<% @jobs.group_by(&:employer_name).sort.each do |employer, jobs| %>
<%= link_to employer, jobs_path() %> <%= "(#{jobs.length})" %>
<% end %>
但是,当我重构视图的代码并将逻辑移至帮助器时,代码无法按预期工作。
view:
<%= employer_filter(@jobs_clone) %>
helper:
def employer_filter(jobs)
jobs.group_by(&:employer_name).sort.each do |employer,jobs|
link_to employer, jobs_path()
end
end
生成以下输出:
<Job:0x10342e628>#<Job:0x10342e588>#<Job:0x10342e2e0>Employer A#<Job:0x10342e1c8>Employer B#<Job:0x10342e0d8>Employer C#<Job:0x10342ded0>Employer D#
我不明白什么?乍一看,代码似乎是等效的。
The following view code generates a series of links with totals (as expected):
<% @jobs.group_by(&:employer_name).sort.each do |employer, jobs| %>
<%= link_to employer, jobs_path() %> <%= "(#{jobs.length})" %>
<% end %>
However, when I refactor the view's code and move the logic to a helper, the code doesn't work as expect.
view:
<%= employer_filter(@jobs_clone) %>
helper:
def employer_filter(jobs)
jobs.group_by(&:employer_name).sort.each do |employer,jobs|
link_to employer, jobs_path()
end
end
The following output is generated:
<Job:0x10342e628>#<Job:0x10342e588>#<Job:0x10342e2e0>Employer A#<Job:0x10342e1c8>Employer B#<Job:0x10342e0d8>Employer C#<Job:0x10342ded0>Employer D#
What am I not understanding? At first blush, the code seems to be equivalent.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一个示例中,它直接输出到 erb,在第二个示例中,它返回该方法的结果。
试试这个:
然后在视图中这样调用它:
还要注意“raw”的使用。一旦你将字符串的生成移出模板,你需要告诉rails你不希望它被html转义。
为了额外的好处,您可以使用“注入”命令而不是显式构建字符串,但我很懒,想给您我知道无需测试即可工作的内容。
In the first example, it is directly outputting to erb, in the second example it is returning the result of that method.
Try this:
Then call it like this in the view:
Also note the use of "raw". Once you move generation of a string out of the template you need to tell rails that you don't want it html escaped.
For extra credit, you could use the "inject" command instead of explicitly building the string, but I am lazy and wanted to give you what I know would work w/o testing.
这个语法正如我所希望的那样工作:
This syntax worked as I hoped it would: