Rails ActiveAdmin. 如何设置默认值?

16

我有这样的代码:

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

我希望将字段:published_at(即t.datetime)默认设置为当前日期和时间。我的示例无法正常工作。我该如何实现这一目标?

2个回答

36

好的,我自己找到了答案。

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

14
需要翻译的内容:值得注意的是,该表单不仅用于编辑现有记录,还用于创建新记录,因此最好使用条件赋值来避免意外覆盖 published_at 的现有值 - 例如,f.object.published_at ||= DateTime.now - omnikron
4
f.object.published_at = DateTime.now unless f.object.persisted? 这段代码仅为新对象分配默认值。它不会覆盖现有对象的空值。 - Dmitry Ukolov

10

您可以尝试类似于这样的内容:

<%= f.input :published_at, input_html: {value: "#{Time.now}"} %>

1
它不起作用。同时也没有抛出任何错误。但是你为什么要使用erb语法?这是app\admin文件夹中的post.rb文件。而你的变量当然会抛出一个错误。所以我尝试了这样:f.input :published_at, input_html: {value: "#{DateTime.now}"}。同样将Time更改为DateTime。还有这样:f.input :published_at, input_html: {value: DateTime.now} - Seybo Glaux
我已经找到答案了。请看我的评论。 - Seybo Glaux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接