0
2

More than 3 years have passed since last update.

【rails】each文で@postsの要素を配列として並べる書き方

Posted at

どうも、岩城です。

みなさん、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文は配列がある場合に非常に便利なのでマスターしちゃいましょう!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2