如何处理具有多个关联级别的表单

时间:2017-12-30 04:34:05

标签: ruby-on-rails

我有以下模型层次结构:

User
  belongs_to :company
  has_many :locations

所以我有一个包含以下元素的表单:

  1. 用户名
  2. 公司名称
  3. 公司位置的3个下拉列表
  4. 我不确定如何创建用户,然后创建公司并将位置与该公司关联。

1 个答案:

答案 0 :(得分:0)

如果您使用simple_form gem并使用cocoon gem,则需要具有类似下面的内容。这将有助于您添加位置并为用户设置公司

= simple_form_for @user do |f|
    = f.input :username
    = f.input :company, collection: @companies
    %h3 Locations
    #locations
      = f.simple_fields_for :locations do |location|
        = render 'location_fields', f: location
      .links
        = link_to_add_association 'add location', f, :locations
    = f.submit

这里location_fields是另一个部分。你需要有一个部分_location_fields

SimpleForm: https://github.com/plataformatec/simple_form
Cocoon: https://github.com/nathanvda/cocoon