ruby,simple_form Rails,集合

时间:2013-10-10 15:26:22

标签: ruby-on-rails ruby simple-form

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

我必须在模型中声明一个包含[“兄弟”,“女儿”,“父亲”,“朋友”,“丈夫”,“母亲”,“姐妹”,“儿子”,“妻子”的变量]并在此处使用:

= 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

请帮帮我!

1 个答案:

答案 0 :(得分: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

或者您可以将此数组提取为单独的服务对象,但在这种情况下,它感觉就像过度工程化。