👋

姓と名のカラムを結合して表示させたい

2023/07/20に公開

🍍今回の悩み


こんな感じの会員一覧ページを作ろとしている。
ひとまず、一通りの記述を下記のように行った。

customers/index.html.erb
<main>
  <h4>会員一覧</h4>
   <table>
     <thead>
      <tr>
        <th>会員ID</th>
        <th>氏名</th>
        <th>メールアドレス</th>
        <th>ステータス</th>
      </tr>
      <tbody>
       <% @customers.each do |customer| %>
        <tr>
           <td><%= customer.id %></td>
           <td><%= link_to customer.last_name, admin_customer_path(customer) %></td>
           <td><%= customer.email %></td>
           <td><%= customer.is_deleted %> </td>
        </tr>
       <% end %>
      </tbody>
     </thead>
   </table>
</main>

この時はカラムを苗字と名前で分けて作っているのを忘れていたから、あ!そうだった名前のカラムも記述しなきゃって思って
<%= link_to customer.last_name,customer.first_name admin_customer_path(customer) %>
こうやって書いたんだけど当然受け付けてもらえないよね😢

🍍解決方法

customerモデルにメソッドを作成

models/customer.rb
 def full_name
    self.last_name + " " + self.first_name
  end

ビューを書き換える

customers/index.html.erb
()
 <td><%= link_to customer.full_name, admin_customer_path(customer) %></td>
()

これで、姓と名が同時に表示されるようになりました!

<p><%= @customer.last_name %> <%= @customer.first_name %></p>

上記のような書き方でも姓と名を横並びに表示することはできるみたいですが、私のようにlink_toもつけたいとなるとメソッド化するほうがよさそうです😻

🍍参考

https://nllllll.com/ruby-on-rails/【rails】「last_name」「first_name」-「姓」「名」をくっつけて表/

Discussion