How to wrap every select of date_select with a div in Rails?

后端 未结 5 1911
抹茶落季
抹茶落季 2020-12-19 01:08

I\'m using Ruby on Rails 3 to create a form for the user, where he can save his birthdate. All the actions around the controller and model work just fine. But I\'m having tr

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 01:25

    In How to let custom FormBuilder wrap datetime_select's selects in e.g. a div? I basically face the same problem.

    JavaScript is not an option for me and the date_separator hack is ... a hack :)

    I came up with the following solution (works for me, in HAML). I think it is the cleanest solution so far but relies on some Rails internals.

    - date_time_selector = ActionView::Helpers::DateTimeSelector.new(Time.current,
                { prefix: @usage.model_name.param_key,
                  field_name: :starttime.to_s,
                  include_position: true })
    .select
      = date_time_selector.select_year
    .select
      = date_time_selector.select_month
    .select
      = date_time_selector.select_day
    .select
      = date_time_selector.select_hour
    .select
      = date_time_selector.select_minute
    

    All you have to do is adjust the prefix (@usage in my case) and the field_name (Attribute-name, @usage.starttime / starttime in my case). In this example, I wrap the corresponding date fields in a div of class "select".

    For reference, there are many more options to play with, here are links to the relevant code:

    • https://github.com/rails/rails/blob/2c97fbf6503c9199f3fe5ed06222e7226dc6fcd9/actionview/lib/action_view/helpers/tags/date_select.rb (FormBuilders will use this path)
    • https://github.com/rails/rails/blob/2c97fbf6503c9199f3fe5ed06222e7226dc6fcd9/actionview/lib/action_view/helpers/date_helper.rb (the real meat)

提交回复
热议问题