![](/img/trans.png)
[英]Rails form with nested attributes (accepts_nested_attributes_for)
[英]Rails accepts_nested_attributes_for - Simple Forms form
我有以下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
@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.