枚举选择在rails中

时间:2016-09-19 20:50:15

标签: ruby-on-rails ruby

我在表单中选择枚举值时出现问题 这是表格

  =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'

在我的数据库中,我有一个字符串类型的字段部门,也在我有的模型中

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

当我发送此表格时 - 在参数中一切正常(部门参数在那里),我也允许在控制器中使用此参数。我仍然接受&#34;部门不能空白&#34;。哪里错了?

1 个答案:

答案 0 :(得分:2)

我认为你将enum作为String接收,所以你应该用setter方法转换它:

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