必须在我的验证/错误消息之间进行选择或按其他属性排序

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

我会尽可能地解释这一点,并且我花了很多时间来确保这不是重复,但如果我忽略了某些事情,我会道歉。我遇到的问题相当简单,它处理的是我在使用cocoon处理嵌套属性时可以传递simple_fields_for的参数数量。没有手动添加一些代码来创建错误通知,我没有得到任何东西,所以我不得不设置如下代码:

Course Model

class Course < ApplicationRecord
  has_many :learning_objectives, dependent: :destroy, inverse_of: :course
end

Learning Objective Model

class LearningObjective < ApplicationRecord
  belongs_to :course, touch: true
  scope :sorted, -> { order(:sort) }
end

Form That Uses f.error_notification

= simple_form_for(@course) do |f|
  = f.error_notification
  .row
    .col-md-12 Learning Objectives
      = f.simple_fields_for :learning_objectives, f.error_notification do |objective|
        = render 'learning_objective_fields', f: objective
      = link_to_add_association 'Add Another Objective', f, :learning_objectives, class: 'btn btn-default btn-sm', data: { association_insertion_node: '.objectives', association_insertion_method: :append }

Learning Objectives Partial

.nested-fields
  .table
    .row
      .col-md-8
        = f.input :name, label: false
      .col-md-2
        = f.input :sort
      .col-md-2.spaced-out
        =link_to_remove_association 'Remove Objective', f, class: 'btn btn-danger btn-xs'

这很好地在嵌套字段上获得必要的通知。但是,我之前在f中使用simple_fields_for就像你在这里看到的:

Form That Uses f.object.learning_objectives.order(:sort)

= simple_form_for(@course) do |f|
  = f.error_notification
  .row
    .col-md-12 Learning Objectives
      = f.simple_fields_for :learning_objectives, f.object.learning_objectives.order(:sort) do |objective|
        = render 'learning_objective_fields', f: objective
      = link_to_add_association 'Add Another Objective', f, :learning_objectives, class: 'btn btn-default btn-sm', data: { association_insertion_node: '.objectives', association_insertion_method: :append }

当我删除那个排序时,它会恢复到最初排序的方式,这并不理想。所以问题在于我一次只能使用其中一个参数,而且我不确定是否有可能使用一个方法来为嵌套属性的f对象使用多个参数。

也许有一种方法可以简单地执行此操作,并且我还将使用相同的标题来交叉堆栈溢出,以查看它们是否有建议,以防这种情况过于具体而无法在此处引发问题。非常感谢您提出的任何建议或方向,并感谢您的宝石!

ruby-on-rails ruby error-handling simple-form cocoon-gem
1个回答
0
投票

这很奇怪。除非我感到困惑,否则simple_fields_for的第二个参数只能是嵌套项的数组,如果没有给出,它只会检查关系/关联。所以我不明白传递f.error_notification(这是错误的直观表示)是如何工作的,除非fields_for只是跳过它,因为它是一个字符串而不是一个可枚举的。

其次:如果你调用order它会尝试使用sql命令,所以它确实只显示数据库中存储的项目。如果您只是尝试对数组进行排序,它就会像您期望的那样工作。例如。就像是

 f.object.learning_objectives.to_a.sort{|x,y| x.sort <=> y.sort}
© www.soinside.com 2019 - 2024. All rights reserved.