LoginSignup
8
9

More than 3 years have passed since last update.

価格登録すると、その数字に「桁区切り」と「円」を追加するプログラムの実装方法

Posted at

1.桁区切り」と「円」を追加するプログラムの実装の手順

ヘルパーメソッドconverting_to_jpyと使って、価格の数字に「桁区切り」と「円」を追加するプログラムを実装する。そして、その表示をビューに表示させる方法について書きます。

実装の手順としては、
1.product_helper.rbにヘルパーメソッドconverting_to_jpyを定義すること。
2.次にindex.html.erbを編集すること。

2.product_helper.rbにヘルパーメソッドconverting_to_jpyを定義する


app/helpers/products_helper.rb

module ProductsHelper
  def converting_to_jpy(price)
    "#{price.to_s(:delimited, delimiter: ',')}円"
  end
end

3.index.html.erbを編集する


<p id="notice"><%= notice %></p>

<h1>Products</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= converting_to_jpy(product.price) %></td>
        <td><%= link_to 'Show', product %></td>
        <td><%= link_to 'Edit', edit_product_path(product) %></td>
        <td><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Product', new_product_path %>

                    

以上にような、実装を行うことで、価格の数字に「桁区切り」と「円」を追加するプログラムの実装が完了する。例えば「1000」という数値が引数で与えらたら「1,000円」といったようにビューに表示される。
                               以上

8
9
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
8
9