2

我有形式:

<%= 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)

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

4

2 回答 2

4

一般来说,如果您需要在将数据保存到数据库之前稍微更改用户在表单中输入的数据,您可以在 Rails 中使用ActiveRecord 回调(例如before_save. 例如,您可能有以下内容:

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在实例上运行私有回调方法,如果它当前是其中的字符串之一,则更改属性(但您应该根据需要调整此逻辑——我只是猜测您可能想要什么)。Eventrepeat['none', 'daily', 'monthly', 'yearly']

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

于 2013-04-07T08:08:04.003 回答
1

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

  before_save do
    self.repeat = Event.rule(self.date, self.repeat )
  end
于 2013-04-07T08:07:52.707 回答