Rails accepted_nested_attributes_for - 简单表单表单

问题描述 投票:0回答:1

我有以下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

ruby-on-rails rails-activerecord simple-form
1个回答
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 %>
© www.soinside.com 2019 - 2024. All rights reserved.