编辑表单不抓取使用的值

时间:2014-03-05 13:33:08

标签: ruby-on-rails ruby activeadmin formtastic

我有一个表格(formtastic)使用Date :: DAYNAMES帮助器在选择框中输出星期几

days = Date::DAYNAMES
q.input :day,
collection: days,
as: :select

这可以工作并输出从星期日开始的星期几,但是当编辑相同的表格时,相关字段不记得我之前选择的那一天,它只返回相同的下拉列表(默认为空白场)

表格

# Activity Date/Time Entry
f.inputs class: 'activityDayTime' do
  f.has_many :activity_dates do |q|
    days = Date::DAYNAMES
    if q.object.new_record?
      q.input :day,
              collection: days,
              as: :select
      q.input :time_from
      q.input :time_to
    else
      q.input :day,
              collection: days,
              as: :select
      q.input :time_from
      q.input :time_to
      q.input :_destroy,
              as: :boolean,
              required: :false,
              label: 'Remove Day/Time'
    end
  end
end

如何将表单默认为编辑表单中保存的日期。

任何帮助表示赞赏

修改

在检查数据库之后,似乎实际上保存的天数(显示为零),因此Date :: DAYNAMES保存到日期字段似乎有问题

编辑2

我已将日期字段更改为字符串字段,但该日仍保存为nil

1 个答案:

答案 0 :(得分:1)

# app/helpers/collection_helper
module CollectionHelper
  def days_collection
    (0..6).map { |wday| [Date::DAYNAMES[wday], wday] }
  end
end

# app/views/posts/_form.html.erb
. . .
  = select_tag :month, options_for_select(days_collection, Time.now.day) # or collection helper
  # simple_form
  = f.input :month, as: :select, collection: days_collection
  # formastic
  = f.input :author, as: :select, collection: days_collection
. . .

说明:

一天在rails中存储为整数

Post.first.created_at.wday # => 2

因此我们需要将日期名称与其号码相关联

Date::DAYNAMES
=> [ "Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" ]

我们可以用代码(它的一个实现)来实现

(0..6).map { |wday| [Date::DAYNAMES[wday], wday] }
# => [ [ "Sunday", 0],[ "Monday",1], ["Tuesday", 2], # end etc

这是数组的格式,也是形式化和简单形式的集合构建器所需的 希望它有所帮助。