Reputation: 33755
I have a PortStock.rb
model, that has the following enum:
class PortStock < ApplicationRecord
enum action: [ :buy, :sell ]
end
What I want to do is on my form partial, I want to include either PortStock.buy
or PortStock.sell
as a hidden field (this will be determined by the params sent with the form).
I don't know what to put in the value:
attribute of my input_field
below.
<%= f.input_field :action, as: :hidden, value: ??? %>
Thoughts?
Upvotes: 1
Views: 601
Reputation: 21130
The documentation says the following:
...
Finally, it's also possible to explicitly map the relation between attribute and database integer with a hash:
class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 } end
Note that when an array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array. In the example,
:active
is mapped to0
as it's the first element, and:archived
is mapped to1
. In general, thei
-th element is mapped toi-1
in the database.Therefore, once a value is added to the enum array, its position in the array must be maintained, and new values should only be added to the end of the array. To remove unused values, the explicit hash syntax should be used.
In rare circumstances you might need to access the mapping directly. The mappings are exposed through a class method with the pluralized attribute name, which return the mapping in a
HashWithIndifferentAccess
:Conversation.statuses[:active] # => 0 Conversation.statuses["archived"] # => 1
...
This means you can solve your problem in 1 of 2 ways.
<%= f.input_field :action, as: :hidden, value: 0 %>
<%= f.input_field :action, as: :hidden, value: PortStock.actions[:buy] %>
Upvotes: 2