我有以下AR模型:
class Branch < ActiveRecord::Base
has_many :branch_delivery_schedules, :class_name => 'BranchDeliverySchedule', :foreign_key => :branch_id
accepts_nested_attributes_for :branch_delivery_schedules, :allow_destroy => true
end
class BranchDeliverySchedule < ActiveRecord::Base
validates :opening_time, :closing_time, presence: true
belongs_to :day_of_week, :class_name => 'DayOfWeek', :foreign_key => :id_day_of_week
belongs_to :branch, :class_name => 'Branch', :foreign_key => :branch_id
end
分支机构有许多交付计划(每天一次,从M到S)。
因此,当我尝试创建新分支时,以分支的形式,为BranchDeliverySchedules设置了simple_fields_for。
<%= simple_form_for(@branch, html: { class: 'form-foodwish' } ) do |f| %>
<%= f.error_notification %>
<!-- BRANCH FIELDS... -->
<% (1..7).each do |w| %>
<%= simple_fields_for 'branch[branch_delivery_schedules_attributes][]', BranchDeliverySchedule.new({ day_of_week: w, opening_time: '11:00', closing_time: '11:00' }) do |p| %>
<%= p.input :id, as: :hidden %>
<%= p.input :branch_id, as: :hidden %>
<!-- DAY OF WEEK PLACEHOLDER -->
<%= p.input :day_of_week, as: :hidden, input_html: { value: w } %>
<%= p.input :opening_time, as: :time, html5: true %>
<%= p.input :closing_time, as: :time, html5: true %>
<% end %>
<% end %>
<% end %>
然后我的控制器中有很强的参数:
def branch_params
params.require(:branch).permit(:id, ..., branch_delivery_schedules_attributes: [ :id, :opening_time, :closing_time, :day_of_week, :branch_id] )
end
一切正常,正在创建7个交货计划。问题是:
1.-如何显示分行交货时间表验证错误? (现在,它只是默默地失败了,不允许我保存分支,这很好,但是我需要显示验证错误)
2.-如何提交simple_fields_for
中的值?当我提交表单时,时间选择器中的值丢失了。
谢谢,如果您需要更多信息,请告诉我。
Rails版本:4.2.6
简单表格版本:3.4.0
答案 0 :(得分:0)
@branch = Branch.new
(1..7).each { |w| @branch.branch_delivery_schedules.new(day_of_week: w, opening_time: '11:00', closing_time: '11:00') }
<%= f.simple_fields_for :branch_delivery_schedules do |p| %>
<%= p.input :day_of_week, as: :hidden, input_html: { value: p.object.day_of_week } %>
<%= p.input :opening_time, as: :time, html5: true %>
<%= p.input :closing_time, as: :time, html5: true %>
<% end %>