I receive from the database the entire list.

#<ActiveRecord::Relation [#<Item id: 1, name: "AAA", unit_price: 10000><#Item ....] 

Next, I need to go through a loop or an iterator and divide the value of unit_price by 100, write the result back and display it in view.

I try this:

 def index @items = Item.all @items.each{ @items[unit_price] = @items[unit_price] /100 } end 

In response, I get:

undefined local variable or method `unit_price '

I look in manual hashes

 user = {name:"Vasya", last_name: "Petrov", age: 20} user[:name] #=> "Vasya" 

and try this:

 def index @items = Item.all @items.each{ @items[:unit_price] = @items[:unit_price] /100 } end 

getting an answer

no implicit conversion of Symbol into Integer

Probably the value of @items [: unit_price], it does not consider the integer, although in the database it is ok ...

  def index @items = Item.all @items.each{ @items[:unit_price] = @items[:unit_price].to_i /100 } end 

getting an answer

no implicit conversion of Symbol into Integer

So @ items.unit_price also tried, there is no such method unit_price

How to sort through these arrays and how to access the necessary fields?

  • Do you want to change the values ​​in the database? Or do you just want to display them on the modified page? - Mikhail Vaysman
  • Display on the page modified - Sergei R
  • you have the price in whole units of 456, and you want to display them in the form of 4.46? - Mikhail Vaysman
  • @ Mikhail Yes, I do not want to use decimal - Sergei R
  • Everything is very, very bad with Ruby. In particular, you do not understand how each works, you would at least read the language site . - D-side

2 answers 2

You do not need to change the values ​​in the collection. You need to use the correct helper and partial when output. Create a partial (_item.html.erb) to display one element and use something like a helper :

 <%= number_to_currency(item.unit_price / 100.0) %> 

But mostly view

 <%= render @items %> 

The best option would be to use gem draper or keynote

    Need to go through the skin element

     def index @items = Item.all @items.each do |item| item[:unit_price] /= 100 item.save # + сохранение в бд end end 

    Updated the answer !!

    • you don’t need to change the database entry - Mikhail Vaysman
    • @MikhailVaysman well, this is an example. I didn't like rewriting the array as an option - x_ror
    • I need to get the same output as @items but the unit_price field: 10,000 should eventually take the form 100.00 - Sergei R
    • @SergeiR so divide by 100 and do not save. it will only work for view - x_ror