如何使用简单表单将特定枚举值指定为隐藏字段?

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

我有一个 PortStock.rb 模型,它有以下枚举:

class PortStock < ApplicationRecord    
  enum action: [ :buy, :sell ]
end

我想做的是在我的部分表单上,我想包含 PortStock.buyPortStock.sell 作为隐藏字段(这将由随表单发送的参数决定)。

我不知道在下面我的 input_fieldvalue: 属性中放什么。

<%= f.input_field :action, as: :hidden, value: ??? %> 

想法?

documentation 表示如下:

...

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

...

这意味着您可以通过 2 种方法中的一种来解决您的问题。

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