Ruby on rails 使用非空白字段的表单创建/新建视图
假设我有一个定期审查资源。我需要的是,当用户转到新的定期审查表单时,表单字段将填充除日期字段之外的最后一个定期审查字段。(想象一下,从一个每日审查到另一个审查,字段不会有太大变化)。我在控制器上有这个:Ruby on rails 使用非空白字段的表单创建/新建视图,ruby-on-rails,Ruby On Rails,假设我有一个定期审查资源。我需要的是,当用户转到新的定期审查表单时,表单字段将填充除日期字段之外的最后一个定期审查字段。(想象一下,从一个每日审查到另一个审查,字段不会有太大变化)。我在控制器上有这个: def new @periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first @periodic_review.date = nil end 这一观点: &
def new
@periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first
@periodic_review.date = nil
end
这一观点:
<%= form_for(@periodic_review) do |f| %> ...
低于日期=零,但会崩溃
如果表单未使用id字段,它如何知道它是更新还是创建?我的方法是:
# rails < 3.1
new_record = old_record.clone
#rails >= 3.1
new_record = old_record.dup
last_periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first
options = last_periodic_review.attributes.merge({ date: nil })
@periodic_review = PeriodicReview.build(options)
我认为这比克隆一个物体更清楚
@periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first.dup
last_periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first
options = last_periodic_review.attributes.merge({ date: nil })
@periodic_review = PeriodicReview.build(options)