我有rails first_or_initialize方法的问题。我有模型本地化,其中有很多开放时间。在我的模型本地化中,我有代码:
has_many :opening_hours
accepts_nested_attributes_for :opening_hours, reject_if: proc { |attributes| attributes['from_time'].blank? }, allow_destroy: true
after_initialize :build_opening_hours
def build_opening_hours
if self.new_record?
self.opening_hours.first_or_initialize(day: "monday", from_time: nil, to_time: nil)
self.opening_hours.first_or_initialize(day: "tuesday", from_time: nil, to_time: nil)
end
end
问题是这个build_opening_hours方法只用day来初始化对象:“monday”第二个对象有一天:“tuesday”没有初始化。怎么了?我无法理解为什么......
答案 0 :(得分:0)
感谢所有帮助我的人。我有模型本地化:
class Localization < ActiveRecord::Base
has_many :opening_hours
accepts_nested_attributes_for :opening_hours, reject_if: proc { |attributes| attributes['from_time'].blank? }, allow_destroy: true
after_initialize :build_opening_hours
def build_opening_hours
if self.new_record?
self.opening_hours.first_or_initialize(day: "monday", from_time: nil, to_time: nil)
self.opening_hours.first_or_initialize(day: "tuesday", from_time: nil, to_time: nil)
end
end
end
这个模型有很多opens_hours。我的模型opening_hours看起来像这样:
class OpeningHour < ActiveRecord::Base
belongs_to :localization
validates :to_time, :from_time, presence: true
end
现在我的目标是当我尝试创建新的本地化以使7个opening_hours对象与此本地化相关联时,例如:“星期一”,“星期二”等。 我创建新本地化的表单如下所示:
= simple_form_for [:partners, @localization] do |f|
= f.input :name
= f.input :address
= f.input :city
= f.input :zip_code
= f.input :phone_in_hours
= f.input :phone_after_hours
= f.input :email
= f.input :email2
= f.input :substitution_cost_in_hours
= f.input :return_cost_in_hours
#checkbox
= check_box_tag 'after_hours_checkbox', 1, true
%b= t('localizations.after_hours')
.disabled
= f.input :return_cost_after_hours
= f.input :substitution_cost_after_hours
= f.input :information
%table.table.table-striped.table-bordered#localizations
%thead
%tr
%th Czynne
%th Dzień tygodnia
%th Otwarte od
%th Otwarte do
%tbody
= f.simple_fields_for :opening_hours do |t|
%tr
%td
%td
= t.input :day
%td
= t.input :from_time, as: :string, :input_html => { :class => 'from_time' }
%td
= t.input :to_time, as: :string, :input_html => { :class => 'to_time' }
= f.submit t('localizations.add'), class: "btn btn-primary"