[英]Rails accepts_nested_attributes_for - Simple Forms form
I have the following AR models: 我有以下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
A branch has many delivery schedules (one per day, M to S). 分支机构有许多交货时间表(每天一个,从M到S)。
So, in the branch's form when I'm trying to create a new branch I set the simple_fields_for for the BranchDeliverySchedules. 因此,在尝试创建新分支时,以分支的形式,我为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 %>
Then I have the strong parameters in my controller: 然后我的控制器中有很强的参数:
def branch_params
params.require(:branch).permit(:id, ..., branch_delivery_schedules_attributes: [ :id, :opening_time, :closing_time, :day_of_week, :branch_id] )
end
And everything is working fine, the 7 delivery schedules are being created. 一切正常,正在创建7个交货计划。 The Questions are:
问题是:
1.- How can I show the Branch delivery schedule validation errors? 1.-如何显示分行交货时间表验证错误? (Right now it just silently fails, doesn't let me save the branch which is good but I need to show the validation errors)
(现在它只是默默地失败了,不允许我保存分支,这很好,但是我需要显示验证错误)
2.- How can I preserve the values in my simple_fields_for
?, when I submit the form the values in the time pickers are lost. 2.-如何在我提交表单时将值保留在时间选择器中而丢失的
simple_fields_for
?
Thanks, let me know if you need more information. 谢谢,让我知道您是否需要更多信息。
Rails version: 4.2.6 Rails版本:4.2.6
Simple form version: 3.4.0 简单表格版本:3.4.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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.