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

Ruby on rails 在保存到db之前,如何更改表单字段值?,ruby-on-rails,forms,action,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 /> <%

我有以下表格:

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

在将重复字段保存到数据库之前,可以在何处以及如何修改重复字段

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

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

一般来说,如果在将数据保存到数据库之前需要稍微更改用户在表单中输入的数据,可以在Rails中使用
before\u 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
class事件
在将
事件
实例保存到数据库之前,这将始终在该实例上运行
set\u repeat
私有回调方法,并且如果
repeat
属性当前是
['none'、'daily'、'monthly'、'year']中的一个字符串,则会更改该属性。
(但你应该根据需要调整这个逻辑——我只是猜测你可能想要什么)


因此,我将研究在保存模型属性之前修改模型属性的一般方法。

什么是
Event.repeat
返回?这是否应该是
self.repeat
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