以下是在主页索引窗口中显示帖子的控制器方法,其中描述了模板:
@sections = ['technology', 'nature']
@briefsections = [['','','','',''], ['','','','','']]
@sections.each_with_index do |section, i|
@tag = Tag.where(name: section).first_or_create!
@tag.posts.each_with_index do |post, num|
@briefsections[i][num] = post || []
end
end
每个帖子都有标签,所以每个标签都有帖子,我应该添加在降序创建的order_by,以及一个只抓取5个帖子的分隔符。 和视图模板
<% @sections.each do |section| %>
<% @briefsections.each do |post| %>
<%= post.title %>
<% end %>
<% end %>
我以前有这样的控制器方法,但是在错误决定更改它之后,尽管该错误只有很多技巧要包括:
@sections = ['technology', 'nature']
@briefsections = ['', '']
@sections.each_with_index do |section, i|
@tag = Tag.where(name: section).first_or_create!
@briefsections[i] = @tag.posts || []
end
在服务器启动时从浏览器查看时,第一个会出现此错误:
undefined method `title' for ["", "", "", "", ""]:Array
第二个在相同情况下也会产生此错误:
undefined method `title' for #<ActiveRecord::Associations::CollectionProxy []>
我宁愿在控制器中抓住它们,也不想遍历模板上的循环,因为我需要在另一个控制器窗口中重新使用该方法。
我习惯于python,您可以将其插入数组。如果这也是一条可能的命令,那么我只需要5个帖子,只需从变量中获取那么多就可以将其固定为集合代理而不是其自己的活动记录模型。
如何可靠地浏览多个对象,以便在模板中对其进行迭代。嵌套的for循环对于易于重现的显示层次结构是必不可少的,这是div结构的最常见用法,因此克服此障碍可适用于更多项目。