Rails accepts_nested_attributes_for-简单表单表单

时间:2018-09-06 23:21:06

标签: ruby-on-rails rails-activerecord simple-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

1 个答案:

答案 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 %>