2017-12-31 277 views
1

Railsでコントローラ経由で記事を作成する。多かれ少なかれ簡単な方法。ただ、いくつかの他の場所からのメソッドを呼び出し、それがバックエンドを経由して新しい記事を作成し、値を埋め:Rails:コントローラーを経由して1つのレコード属性を新しいレコードに送信できますが、配列に送信できないのはなぜですか?

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はただ一つのレコードである場合、これは正常に動作してに、既存の記事本文を印刷します新品本体です。ビュー内で右に見えると右 "編集"に見えます。すべて完璧です。

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

とIn:

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

しかし、私は最後の10件の記事と同じことをしようとした場合、それは動作しません:あなたが得るビューで

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. 

何もない知ってる?私は何が欠けていますか?

答えて

0

をので、@Shikoは確かに正しい道の上に、ほぼ正しかったです。配列を少し操作し、それを動作させるために二つのことをしなければならなかった:

  1. .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 
0

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 
+0

を我々はすべての恩恵を受けることができますので、間違っているものに説明を追加してください。 – Shiko

+0

ありがとう@シコ、それは正しい道に私を得た。しかし、もう少し微調整しました。答えを見てください。 –

関連する問題