查询的描述
我将视图中使用的一些逻辑转移到了一个View助手。完全相同的逻辑,但没有得到相同的结果,我得到一个哈希返回而不是解析的数据。
语言版本
/Gemfile
ruby '2.6.5'
gem 'rails', '~> 6.0.1'码
->主计长
/app/controllers/blogs_controller.rb
def index
@search = ""
if params[:section]
@posts = Post.in_section(params[:section]).where(status: "published").includes(member: [:profile]).reverse
elsif params[:category]
@posts = Post.categorized_as(params[:category]).where(status: "published").includes(member: [:profile]).reverse
elsif params[:tag]
@posts = Post.tagged_with(params[:tag]).where(status: "published").includes(member: [:profile]).reverse
else
@posts = Post.where(status: "published").includes(member: [:profile]).reverse
end
@sections = Section.where(id: SectionBlogMap.all.select(:section_id)).select(:id, :name, :slug, :order).sort_by{|o| o[:order]}
@categories = Category.where(id: CategoryMap.all.select(:category_id)).select(:id, :name, :slug).sort_by{|n| n[:name]}.to_a
@tags = Tag.where(id: TagMap.all.select(:tag_id)).select(:id, :name, :slug).sort_by{|n| n[:name]}.to_a
end->“帮手”
/app/helpers/posts_helper.rb
def tag_links(tag_name, tag_slug)
link_to tag_name, tag_path(tag_slug)
end
def tag_links2(tags)
tags.each do |tag|
link_to tag.name, tag_path(tag.slug)
end
end->视图
/app/views/blogs/index.html.erb
<h4>Tags</h4>
<p>
<% @tags.each do |tag| %>
<%= link_to tag.name, tag_path(tag.slug) %>
<% end %>
<br/>
<%= tag_links2(@tags) %>
</p>-->结果
**Tags**
Active Blue Red Tag 10 Tag 6 Tag 7 Tag 8 Tag 9 Yellow
[#<Tag id: 1, name: "Active", slug: "active">, #<Tag id: 3, name: "Blue", slug: "blue">, #<Tag id: 5, name: "Red", slug: "red">, #<Tag id: 10, name: "Tag 10", slug: "tag-10">, #<Tag id: 6, name: "Tag 6", slug: "tag-6">, #<Tag id: 7, name: "Tag 7", slug: "tag-7">, #<Tag id: 8, name: "Tag 8", slug: "tag-8">, #<Tag id: 9, name: "Tag 9", slug: "tag-9">, #<Tag id: 4, name: "Yellow", slug: "yellow">]问题
使用byebug,我检查了正在传递的代码和变量,视图与助手之间没有任何变化。因此,我不知道为什么要将each do逻辑移动到帮助程序中。由于我是一个自学的Ruby开发人员,我猜想有一种解释与视图/助手关系相关,而我只是不熟悉这种关系。有人能给我一点启示吗?
发布于 2019-12-07 05:51:58
这是:
def tag_links2(tags)
tags.each do |tag|
link_to tag.name, tag_path(tag.slug)
end
end...returns tags,而不是包含在do块中的link_to方法的结果。
相反,不妨试试:
def tag_links2(tags)
tags.each_with_object("") do |tag, to_return|
to_return << link_to(tag.name, tag_path(tag.slug))
end.html_safe
end您可能不需要在那里使用html_safe。
发布于 2019-12-08 17:34:59
当您在ERB中的循环中运行代码时,每个迭代输出到缓冲区:
<% @tags.each do |tag| %>
<%= link_to tag.name, tag_path(tag.slug) %>
<% end %>实际上就像跑步一样:
@tags.each do |tag|
puts link_to tag.name, tag_path(tag.slug)
end然而,当您在帮助者中时,这种情况不会发生。Rails提供了可用于在帮助程序中输出的合并:
def tag_links2(tags)
tags.each do |tag|
concat link_to tag.name, tag_path(tag.slug)
concat ' ,' unless tag == tags.last
end
endhttps://stackoverflow.com/questions/59223272
复制相似问题