has_and_belongs_to_many with join table和checkbox collection

时间:2018-06-05 19:21:49

标签: ruby-on-rails

我正在尝试制作一个管理页面,其中包含另一个模型的嵌套表单。

我有一个Playbook模型:

playbook.rb

  has_and_belongs_to_many :groups
  accepts_nested_attributes_for :groups

我的表单视图

_form.html.haml

<%= form_with(model: playbook, local: true) do |form| %>

   ...

  <%= collection_check_boxes(:group, :group_ids, Group.all, :id, :name) %>

  <div class="actions">
    <%= form.submit %>
  </div>

为了解释它,Playbooks可以有许多组,这是另一个模型,我想在使用我认为是嵌套形式保存playbook时自动保存到groups_playbooks连接表。我只是不知道如何使用像我的视图一样的复选框来执行嵌套表单。

以下是帮助提供更好图片的架构的一部分:

  create_table "groups", force: :cascade do |t|
    t.string "name"
    t.string "variables"
    t.bigint "server_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["server_id"], name: "index_groups_on_server_id"
  end

  create_table "groups_playbooks", id: false, force: :cascade do |t|
    t.bigint "group_id", null: false
    t.bigint "playbook_id", null: false
  end

  create_table "groups_servers", id: false, force: :cascade do |t|
    t.bigint "group_id", null: false
    t.bigint "server_id", null: false
  end

  create_table "playbooks", force: :cascade do |t|
    t.string "name"
    t.string "play"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "description"
  end

  create_table "playbooks_servers", id: false, force: :cascade do |t|
    t.bigint "playbook_id", null: false
    t.bigint "server_id", null: false
  end

  create_table "servers", force: :cascade do |t|
    t.string "name"
    t.string "ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "group_id"
    t.index ["group_id"], name: "index_servers_on_group_id"
  end

1 个答案:

答案 0 :(得分:2)

根据specification,您应该使用playbook代替groups

<%= collection_check_boxes(:playbook, :group_ids, Group.all, :id, :name) %>

但是,如果您有表单构建器,则应该查看that specification

对于你的情况

<%= form.collection_check_boxes(:group_ids, Group.all, :id, :name) %>
相关问题