Question

In my db i have such field:

color_id

and in form i use such code, to store it in db:

= f.select :color_id, options_for_select([["белый", 1], ["желтый", 2], ["зеленый", 3], ["коричневый", 4], ["красный", 5], ["оранжевый", 6], ["серебристый", 7], ["серый", 8], ["синий", 9], ["фиолетовый", 10], ["черный", 11], ["другой", 12]], :selected => f.object.color_id), {:prompt => "Выберите цвет кузова"}, required: true

so i decide to to without model and db table, just id from html form, and this id store in db.

But how to view in show action not it, but color?

I can do it only with if, like:

- if c.color_id == 1
  белый
- if c.color_id == 2
  желтый

but maybe there is more elegant and good solution? How to change id, to array's color in my case

Was it helpful?

Solution

you can define method color, which will put text based on color_id

def color(color_id)
  colors[color_id]
end

def colors
  ["name1", "name2"]
end

Please note that the array starts from 0, and in your code ids start from 1

OTHER TIPS

You can create a Hash in model having color_id field like following:

COLORS = {"1" => "белый", "2" => "желтый",...}

And then you can call a method in model for getting the print the color

def color
  COLORS[color_id.to_s]
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top