使用带有非空字段的form_for创建/新视图

时间:2012-08-09 16:01:09

标签: ruby-on-rails

说我有一个periodic_review资源。我需要的是,当用户转到新的periodic_review表单时,表单字段将填充除日期字段之外的最后一个periodic_review字段。 (想象一下,从一个daily_review到另一个,每个字段的变化不会太大)。我在控制器上有这个:

  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| %> ...

现在的问题是,因为form_for获取非空的@periodic_review,它会生成更新表单而不是创建表单,从而将用户发送到提交时的更新。我试过了:

@periodic_review.id = nil

低于date = nil,但它崩溃了。

如果表单没有使用id字段,表单如何知道是更新还是创建?

2 个答案:

答案 0 :(得分:1)

# rails < 3.1
new_record = old_record.clone

#rails >= 3.1
new_record = old_record.dup

我的代码,对于rails&gt; = 3.1,

@periodic_review = PeriodicReview.where(user_id: @user_id).order("revision DESC").first.dup

答案 1 :(得分:1)

我这样做的方法:

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)

我认为它比克隆一个对象更清楚。