代码之家  ›  专栏  ›  技术社区  ›  Matthew Bennett

Rails:为什么我可以通过控制器将单个记录属性发送给新记录,而不是数组?

  •  1
  • Matthew Bennett  · 技术社区  · 8 年前

    通过Rails中的控制器创建文章。一种简单的方法,或多或少有效;只需从其他地方调用该方法,它就会通过后端生成一篇新文章,并填写以下值:

    def test_create_briefing
      a = Article.new
      a.type_id = 27
      a.status = 'published'
      a.headline = 'This is a headline'
      a.lede = 'Our article is about some interesting topic.'
      a.body = test_article_text
      a.save!
    end
    

    如果 test_article_text 只是一条记录,这可以很好地将现有的文章正文打印到新的文章正文中。在视图中向右看,在“编辑”中向右看。一切都很完美。

    def test_article_text
      a = Article.find_by_id(181)
      a.body
    end
    

    但是,如果我试图对最后十篇文章做同样的事情,那就行不通了:

    def test_article_text
      Article.lastten.each do |a|
        a.body
      end
    end
    

    在视图中,您可以看到:

    [#, #, #, #, #, #, #, #, #, #]
    

    在“编辑”中,您可以得到:

    [#<Article id: 357, headline: "This is a headline", lede: "Our article is about some interesting topic.", body: "[#<Article id: 356, headline: \"This is a headline\"...", created_at: "2017-12-31 20:40:16", updated_at: "2017-12-31 20:40:16", type_id: 27, urgency: nil, main: nil, status: "published", caption: nil, source: nil, video: nil, summary: nil, summary_slug: nil, topstory: false, email_to: nil, notification_slug: nil, notification_message: nil, short_lede: nil, short_headline: nil, is_free: nil, briefing_point: nil>, #<Article id: 356, headline: "This is a headline"…etc, etc, etc.
    

    我不知道什么?我错过了什么?

    2 回复  |  直到 8 年前
        1
  •  0
  •   Shiko    8 年前

    返回如下,因为 Article.lastten 是从控制器返回的变量。

    [#<Article id: 357, headline: "This is a headline", lede: "Our article is about some interesting topic.", body: "[#<Article id: 356, headline: \"This is a headline\"...", created_at: "2017-12-31 20:40:16", updated_at: "2017-12-31 20:40:16", type_id: 27, urgency: nil, main: nil, status: "published", caption: nil, source: nil, video: nil, summary: nil, summary_slug: nil, topstory: false, email_to: nil, notification_slug: nil, notification_message: nil, short_lede: nil, short_headline: nil, is_free: nil, briefing_point: nil>, #<Article id: 356, headline: "This is a headline"…etc, etc, etc.
    

    要返回所有文章正文,请执行以下操作:

    def test_article_text
      arr = Array.new
      Article.lastten.each do |a|
        arr << a.body
      end
      arr # should be added so it will be the last value returned from your controller
    end
    
        2
  •  0
  •   Matthew Bennett    8 年前

    所以,@Shiko几乎是对的,当然是在正确的道路上。必须稍微操纵阵列,并做两件事才能使其工作:

    1. .join 阵列中的位可以去除所有垃圾;

    2. 以不同于通常在视图中所做的方式连接每篇文章的不同位。所以 to_s 对于每个属性,连接 "" + "" 以及使用数组中的可用信息重建url(否 link_to 等)。

    3. 这个 "**" 是markdown,因为我正在使用它,但我想如果需要的话,您可以在其中插入html标记。

    这项工作:

    def test_article_text
      arr = Array.new
      Article.lastten.each do |a|
      arr << "**" + a.headline.to_s + "**: " + a.text.to_s + "[Read now](/articles/#{a.id}-#{a.created_at.strftime("%y%m%d%H%M%S")}-#{a.headline.parameterize})"
      end
      arr.join("\n\n")
    end