【问题标题】:Rails accepts_nested_attributes_for - Simple Forms formRails 接受_nested_attributes_for - 简单表单表单
【发布时间】:2018-09-06 23:21:05
【问题描述】:

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

    控制器

    @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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多