marcamillion
marcamillion

Reputation: 33755

How do I specify a specific enum value as a hidden field using Simple Form?

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

Answers (1)

3limin4t0r
3limin4t0r

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 to 0 as it's the first element, and :archived is mapped to 1. In general, the i-th element is mapped to i-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.

  1. <%= f.input_field :action, as: :hidden, value: 0 %>
    
  2. <%= f.input_field :action, as: :hidden, value: PortStock.actions[:buy] %>
    

Upvotes: 2

Related Questions