简体   繁体   中英

Set a Rails form hidden field from enum model

I have multiple social networks available in my model:

class Social < ActiveRecord::Base
  enum kind: [ :twitter, :google_plus, :facebook, :linked_in, :skype, :yahoo ]
  belongs_to :sociable, polymorphic: true
  validates_presence_of :kind
  validates_presence_of :username
end

I want to use something like this in my view.

<%= f.fields_for :socials do |a| %>
  <%= a.select  :kind, Social.kinds.keys, selected: :skype %><br />
  Skype ID: <%= a.text_field :username %>
<% end %>

But I want to enforce the kind to be skype and not be user modifiable. So I'm trying to switch it to a hidden_field tag. But I'm not having any luck with it.

So the user should only see the label "Skype ID" with a username input box where they don't see the kind selected in the hidden field.

You can create and set a hidden field like so, and it should work for enum

<%= a.hidden_field :kind, {value: 'skype'} %>

You don't really need it to be a select tag if the user cannot select, or even see the option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM