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

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

我有以下模型层次结构:

User
  belongs_to :company
  has_many :locations

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

  1. 用户名
  2. 公司名
  3. 3个公司位置的下拉列表

我不确定如何创建用户,然后创建公司并将位置关联到该公司。

ruby-on-rails
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.