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

在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"…etc, etc, etc.

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

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

 [#
, #

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

 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 

所以@Shiko几乎是正确的,肯定是在正确的道路上。 不得不操纵数组并做两件事来让它工作:

  1. .join数组中的部分.join所有的垃圾;

  2. 以与通常在视图中不同的方式连接每篇文章的不同位。 所以to_s为每个属性,连接"" + ""并用数组中可用的信息重建url(没有link_to等)。

  3. "**"是降价,因为我正在使用它,但我想如果你需要,你可以在那里打开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