どうも、岩城です。
みなさん、each文は好きですか?好きですよね?違いますか?
さて、そんな私が絶賛片思い中のeach文ですが、railsの中ではどのように使われるのでしょうか。見ていきましょう。
まずはこちらを見てみましょう
<div class="single-post-card">
<div class="card">
<div class="card-block">
<h4 class="post-text">
<%= truncate(post.title, :length => 60) %>
</h4>
<div class="post-content">
<div class="posted-by">Posted by <%= post.user.name %></div>
<h3><%= post.title %></h3>
<p><%= post.content %></p>
<%= link_to "I'm interested", post_path(post.id), class: 'interested' %>
</div>
</div>
</div>
</div>
postの中身をpost.titleなどで呼び出しています。
ただ、これだと複数の要素を自動的に配列として並べる際にややこしくなってしまいます。
railsのeach文をこう書きましょう。
Postscontorollerに
@posts=Post.all
があると仮定して、each文で呼び出していきましょう!
<div id="main-content" class="col-sm-9">
<h3 class="page-name"><%= link_to 'Post', posts_path %></h3>
<div class="row">
<% @posts.each do |post| %>
<div class="col-sm-3 single-post-card" id=<%= post_path(post.id) %>>
<div class="card">
<div class="card-block">
<h4 class="post-text">
<%= truncate(post.title, :length => 60) %>
</h4>
<div class="post-content">
<div class="posted-by">Posted by <%= post.user.name %></div>
<h3><%= post.title %></h3>
<p><%= post.content %></p>
<%= link_to "I'm interested", post_path(post.id), class: 'interested' %>
</div>
</div>
</div>
</div>
<% end %>
</div>
</div>
上記のように書くことで、@postsの1つ1つのカラムをpost.titleなどの表記で呼び出せるようになります。
以上になります^^
each文は配列がある場合に非常に便利なのでマスターしちゃいましょう!