我正在尝试组合表单中的start_date
、start hour
和start_minute
virtual 属性Event
,以创建一个start_datetime
属性(存储在数据库中)。
我(通过 STI)有几个子类Event
;让我们称它们为TrainingSession
andWorkSession
和PersonalTime
。
类的结构如下:
class Event < ActiveRecord::Base
...
end
class TrainingSession < Event
...
end
class WorkSession < Event
...
end
class PersonalTime < Event
...
end
的相关部分event.rb
:
class Event < ActiveRecord::Base
attr_accessor :start_date, :start_hour, :start_minute
validates :start_datetime, :presence => true
before_validation :merge_attributes_for_datetime_string
def merge_attributes_for_datetime_string
start_datetime_string = "#{ start_date } #{ start_hour }:#{ start_minute }:00"
end
def start_datetime=(start_datetime_string)
self.start_datetime = start_datetime_string
end
def start_date
start_datetime.strftime("%d") if start_datetime?
end
def start_hour
start_datetime.strftime("%H") if start_datetime?
end
def start_minute
start_datetime.strftime("%M") if start_datetime?
end
end
...和events_controller.rb
:
def create
@event = Event.new(event_params)
if @event.save
redirect_to :root, :flash => { :success => "Event added." }
else
redirect_to :back, :flash => { :notice => "There was an error creating the event." }
end
end
private
def event_params
params.require(:event).permit(
:type,
:start_datetime,
:start_date,
:start_hour,
:start_minute,
...
)
end
def training_session_params
params.require(:training_session).permit(
...
)
end
def work_session_params
params.require(:work_session).permit(
...
)
end
def personal_time_params
params.require(:personal_time).permit(
...
)
end
我已经在我的服务器日志中验证了正确的参数是从表单发送的:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<TOKEN HERE>=", "event"=>{"start_date" => "2013-08-23", "start_hour"=>"15", "start_minute"=>"00", "type"=>"PersonalTime"}, "commit"=>"Add Personal Time"}
然而,每次我尝试创建一个事件(任何类型)时,我都会收到通知There was an error creating the event.
(根据我的创建方法)。如果我注释掉validates :start_datetime
,则创建事件,但使用start_datetime
of nil
。
这必须意味着start_datetime
字符串没有从虚拟属性中正确合并,但我不知道为什么。
我在这里想念什么?有没有更好的设置方法start_datetime
?