anti-k anti-k - 2 months ago 23
Ruby Question

enum select in rails

I've got a problem with selecting enum value in form
here is a form

=form_for @ticket , remote: true do |f|
.errors
p
= f.label :name, class: 'label_hidden'
= f.text_field :name, placeholder:'Input your name', class:'form-control'
p
= f.label :email, class: 'label_hidden'
= f.email_field :email, placeholder:'Input your email', class:'form-control'
p
= f.label :department, class: 'label_hidden'
= f.select :department, Ticket.departments.keys , class:'form-control'
p
= f.submit 'Submit', class:'btn btn-default custom'


In my db I have a field department that is string type, also in a model I have

class Ticket < ActiveRecord::Base
enum department: [:issue, :qa, :promotion]
validates :name, :email, :subject, :body, :department, presence: true
end


When i send this form - in params everything is ok( the department param is there), also I have permitted this param in controller. Still I recieve "department can't be blank". Where I am wrong?

Answer

I suppose that you receive enum as a String, so you should convert it with setter method:

def department=(val)
    self[:department] = val.to_sym
end