16

I have code like this:

ActiveAdmin.register Post do

form do |f|
  f.inputs "Post Details" do
    f.input :title
    f.input :body
    f.input :published_at, :as => DateTime.now
  end
  f.actions
end

I want the field :published_at (which is t.datetime) to be set to the current date and time by default. My example doesn't work. How can I achieve this?

Seybo Glaux
  • 787
  • 1
  • 7
  • 16

2 Answers2

36

Yep. Found the answer myself.

ActiveAdmin.register Post do

form do |f|
  f.object.published_at = DateTime.now
  f.inputs "Post Details" do
    f.input :title
    f.input :body
    f.input :published_at
    ...
  end
end
Seybo Glaux
  • 787
  • 1
  • 7
  • 16
  • 14
    It is worth noting that the form is used for editing existing records as well as creating new ones, so it is preferable to use conditional assignment to avoid accidentally overwriting the existing value of `published_at` – ie. `f.object.published_at ||= DateTime.now` – omnikron May 04 '17 at 11:17
  • 4
    `f.object.published_at = DateTime.now unless f.object.persisted?` assings default value only for new object. It will not overwrite empty value for existing object. – Dmitry Ukolov Jan 30 '18 at 19:50
10

You can try with something like this:

<%= f.input :published_at, input_html: {value: "#{Time.now}"} %>
Flamine
  • 487
  • 4
  • 21
  • 1
    it doesn't work. And at the same time it doesn't throw any errors. But why did you use erb syntax? This is the `post.rb` file in `app\admin` folder. And your variant throws an error of course. So I tried it like this: `f.input :published_at, input_html: {value: "#{DateTime.now}"}`. Changed `Time` to `DateTime` as well. And like this: `f.input :published_at, input_html: {value: DateTime.now}` – Seybo Glaux May 22 '16 at 03:33
  • i've found the answer. See my comment. – Seybo Glaux May 22 '16 at 04:04