0

我正在尝试组合表单中的start_datestart hourstart_minutevirtual 属性Event,以创建一个start_datetime属性(存储在数据库中)。

我(通过 STI)有几个子类Event;让我们称它们为TrainingSessionandWorkSessionPersonalTime

类的结构如下:

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_datetimeof nil

这必须意味着start_datetime字符串没有从虚拟属性中正确合并,但我不知道为什么。

我在这里想念什么?有没有更好的设置方法start_datetime

4

1 回答 1

0

根据您发布的内容,我看不到您在哪里调用该start_datetime方法。

您可以在方法中进行合并,而不是定义新方法,start_datetime如下所示:

before_validation :merge_attributes_for_datetime_string

def merge_attributes_for_datetime_string
  self.start_datetime = "#{ start_date } #{ start_hour }:#{ start_minute }:00"
end
于 2013-08-23T21:08:25.677 回答