1

ここでの極端なRuby/Rails初心者:ブロックに含まれる個々の投稿の検索アクションにlink_toしようとしています:

<% split_tags = post.tags.split(',') %> # returns ["food", "computers", "health"] %>
<p>Keywords: <%= split_tags.each {|tag| link_to(tag, front_search_tag_path(:tag => tag))}) %></p>

しかし、返されるのはKeywords: ["food", "computers", "health"]。.eachは配列を反復処理し、タグをパラメーターとして各search_tag_pathへのリンクを提供するべきではありませんか?

4

3 に答える 3

4

いいえ、#eachはブロックを実行するだけで、データは蓄積されません。

[1, 2, 3].each{ |n| "Link to item #{n}" } #=> [1, 2, 3]

2つのオプションがあります。マップを使用してデータを蓄積します。

[1, 2, 3].map{ |n| "Link to item #{n}" }.join("\n") #=> "Link to item 1\nLink to item 2\nLink to item 3"

または、ブロックに直接出力します。

[1, 2, 3].each{ |n| puts "Link to item #{n}" }

プリント:

Link to item 1
Link to item 2
Link to item 3

あなたの場合、これは次の2つのオプションになります。私は後者が好きです。

<p>Keywords: <%=raw split_tags.map{|tag| link_to(tag)}.join %></p>

<p> Keywords:
  <% split_tags.each do |tag| %>
    <%= link_to(tag) %>
  <% end %>
</p>
于 2012-08-16T22:10:40.490 に答える
0

あなたはおそらく意味しました

<% split_tags = post.tags.split(',') %> # returns ["food", "computers", "health"] %>
<p>Keywords:
  <% split_tags.each do |tag| %>
  <%= link_to(tag, front_search_tag_path(:tag => tag)) %>
  <% end %>
</p>

また

<% split_tags = post.tags.split(',') %> # returns ["food", "computers", "health"] %>
<p>Keywords:
  <%= split_tags.map{|tag| link_to(tag, front_search_tag_path(:tag => tag))}.join %>
</p>
于 2012-08-16T22:10:13.207 に答える
0

いいえ、の戻り値Array#eachは配列自体です(http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-eachを参照)

リンクの配列を返すArray#collect(またはそのエイリアス)を使用することをお勧めします( http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-mapを参照)。次に、その配列を結合を使用して単一の文字列に変換できます。したがって、コードは次のようになりますmap

<% split_tags = post.tags.split(',') %>
<p>Keywords: <%= split_tags.collect {|tag| link_to(tag, front_search_tag_path(:tag => tag))}).join %></p>

ただし、.html_safeその後にが必要になる場合があり.joinます。さらに良いことに、次のようなことを行います。

<% split_tags = post.tags.split(',') %>
<p>Keywords: 
<% split_tags.each do |tag| %>
  <%= link_to(tag, front_search_tag_path(:tag => tag)) %>
<% end %>
</p>
于 2012-08-16T22:11:21.557 に答える