如何在保存到db之前更改表单字段值?

时间:2013-04-06 22:34:04

标签: ruby-on-rails forms action

我有表格:

<%= form_for(@event) do |f| %>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :date %><br />
    <%= f.text_field :date %>
  </div>

  <div class="field">
    <%= f.label :repeat %><br />
    <%= repeat_types = ['none', 'daily', 'monthly', 'yearly'] 
        f.select :repeat, repeat_types %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我需要保存到'重复'字段更改数据为:

:repeat = Event.rule(:date,:repeat)

在将重复字段保存到数据库之前,我在哪里以及如何修改重复字段?

2 个答案:

答案 0 :(得分:4)

通常,如果您需要在将表单保存到数据库之前稍微更改用户在表单中输入的数据,则可以使用before_saveActiveRecord callbacks在Rails中执行此操作。例如,您可能具有以下内容:

class Event < ActiveRecord::Base
  before_save :set_repeat

  private
  def set_repeat
    self.repeat = Event.rule(date, repeat) if ['none', 'daily', 'monthly', 'yearly'].include? repeat
  end
end

这将始终在set_repeat实例上运行Event私有回调方法,然后将其保存到数据库中,并更改repeat属性(如果它当前是['none', 'daily', 'monthly', 'yearly']中的一个字符串{1}}(但你应该根据需要调整这个逻辑 - 我只是猜到了你想要的东西)。

因此,在保存模型属性之前,我会将ActiveRecord callbacks作为修改模型属性的一般方法。

答案 1 :(得分:1)

我发现我可以在我的Event模型中使用ActiveRecords回调。如下:

  before_save do
    self.repeat = Event.rule(self.date, self.repeat )
  end