simple_form日期输入不是选择

时间:2014-12-04 13:51:49

标签: ruby-on-rails simple-form

我使用simple_form,我需要将日期选择为3个单独的输入字段(日月)。

这就是我所拥有的,但绝对不是我想要的。

<%= f.date_select :date_of_birth, start_year: Date.today.year - 16,
                            end_year: Date.today.year - 100,
                            order: [:day, :month, :year], label: false %>

感谢您的帮助!

截至目前,我只是假设我必须用DB中的3个字段替换我的date_of_birth,然后简单地编写一个方法将这些组合成实际的出生日期,我认为这条路径是丑陋的,希望那里是更好的一个。

2 个答案:

答案 0 :(得分:0)

尝试

= date_select 'object_name', :date_of_birth

你应该在哪里替换&#39; object_name&#39;用你的对象名称。例如&#39;用户&#39;对于User类,依此类推。

但请记住,这种方法可能会破坏您的标记,因为simple_form会添加自己的div和其他包装来形成字段。所以你也应该添加它们。

答案 1 :(得分:0)

我决定只向数据库添加3个字段:

  t.integer :birth_day
  t.integer :birth_month
  t.integer :birth_year

写一些验证:

  validates :birth_day, 
            numericality: { only_integer: true, message: "Please enter numbers only." }, 
            length: { is: 2, message: "Should be 2 digits." },
            inclusion: { in: 1..31, message: 'should be in range 1..31'}
  validates :birth_month, 
            numericality: { only_integer: true, message: "Please enter numbers only." }, 
            length: { is: 2, message: "Should be 2 digits." },
            inclusion: { in: 1..12, message: 'should be in range 1..31'}
  validates :birth_year, 
            numericality: { only_integer: true, message: "Please enter numbers only." }, 
            length: { is: 4, message: "Should be 4 digits." },
            inclusion: { in: 1900..1996, message: 'should be in range 1900..1996'}

并将方法写入组装日期对象的方法:

  def date_of_birth
    "#{birth_day}/#{Date::MONTHNAMES[birth_month]}/#{birth_year}".to_date
  end
相关问题