【问题标题】:Basic Logic in RailsRails 中的基本逻辑
【发布时间】:2016-02-01 07:32:07
【问题描述】:

我想不通的简单问题:我有一个带有Article 模型的博客应用程序。在我的welcome#index 页面上,我想显示最近发布的四篇文章的每一个标题。

class WelcomeController < ApplicationController

def index
    @articles = Article.all
end
end

在我看来,我需要将每个标题分别显示在其相应的 html 'box' 中。对于第一个标题,我编写了以下代码:

%title #{ @articles.last(1).title }

为此我收到 undefined method 'title' 错误。

知道为什么会这样吗?

【问题讨论】:

  • 使用 @articles = Article.last(4) 获取最后 4 个帖子,然后迭代所有帖子以获得标题。
  • 好的,太好了。如何分别迭代每个标题?
  • @liroy 就用.each方法

标签: ruby-on-rails view controller


【解决方案1】:

@articles.last(1) 将最后一篇文章放在Array 中,就像:

[ #<Artile id: ..> ]

所以你需要像@articles.last(1).first.title 那样做。

如果你真的对上一篇文章感兴趣,你可以做简单的喜欢:

@articles.last.title

因为@articles.last直接给你文章对象:

#<Article id: ..>

要进行迭代,您将使用 .each 之类的:

- @articles.each do |article|
    %title #{ article.title }

在您的控制器中填充@articles,例如:

@articles = Article.order('updated_at asc').last(4)

【讨论】:

  • 每个循环将我的 html 元素乘以四!为什么会这样?
  • @liroy 在单独的问题中显示您的 HTML 代码.. 我们会帮助您
【解决方案2】:

除了 Imran 和 Arup 的答案,如果你真的只需要标题列,你可以像这样查询它@articles = Article.last(4).pluck(:title)

【讨论】:

    【解决方案3】:

    我认为你的代码应该

    @articles = Article.order('updated_at asc').last(4) # Controller
    

    查看

    <% @articles.each do |title| %>
      <%= title.title %> #-> print last 4 title
    <% end %>
    

    希望能帮到你

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多