-1

我有集合(simple_form)的“视图”输入,但该集合应该在模型中。

我必须在模型中声明一个包含 ["Brother", "Daughter", "Father", "Friend", "Husband", "Mother", "Sister", "Son", "Wife"] 的变量并用于在这里查看:

= f.input :relationship

这就是我的观点:

= simple_form_for @emergency_information, html: {class: 'form-horizontal' } do |f|
  = f.error_notification
  = f.input :name
  = f.input :relationship, collection: ["Brother", "Daughter", "Father", "Friend", "Husband", "Mother", "Sister", "Son", "Wife"]

那是我的模特

class EmergencyInformation < ActiveRecord::Base
  belongs_to :user

  validates :user_id, :name, presence: true

end

请帮帮我!

4

1 回答 1

1

如果我理解正确,您的困难是弄清楚该阵列的附加位置。通常在这些情况下,我将它作为常量添加到我的模型中,并将其用于列出值并验证提交的值是否来自数组。

class EmergencyInformation < ActiveRecord::Base
  RELATIONSHIPS_TYPES = ["Brother", "Daughter", "Father", "Friend", "Husband", "Mother", "Sister", "Son", "Wife"]
  belongs_to :user

  validates :user_id, :name, presence: true
  validates :relationship, inclusion: RELATIONSHIPS_TYPES
end

# in view
= f.input :relationship, collection: EmergencyInformation::RELATIONSHIPS_TYPES

或者,您可以提取此数组以分离服务对象,但在这种情况下,感觉就像过度设计。

于 2013-10-10T15:45:51.087 回答