【问题标题】:ActiveAdmin nested has_manyActiveAdmin 嵌套 has_many
【发布时间】:2020-12-03 02:53:57
【问题描述】:

考虑以下模型:

class User < ApplicationRecord
    accepts_nested_attributes_for :memberships, allow_destroy: true

    has_many :memberships, dependent: :destroy
    has_many :accounts, through: :memberships
end

class Account < ApplicationRecord
  accepts_nested_attributes_for :memberships, allow_destroy: true
  accepts_nested_attributes_for :users, allow_destroy: true

  has_many :memberships, dependent: :destroy
  has_many :users, through: :memberships
end

class Membership < ApplicationRecord
  belongs_to :account
  belongs_to :user
  
  before_validation { self.role = "admin" if role.blank? }

  validates :role, presence: true

  pg_enum :role, %i[admin support user]
end

在 ActiveAdmin 中,已经有一个表单可以从现有用户创建帐户和成员资格。看起来像这样:

form do |f|
  ...
  f.inputs do
    f.has_many :memberships, heading: false, allow_destroy: true, new_record: "Add existing user" do |m|
      m.input :user_id, as: :searchable_select, ajax: { resource: User }
      m.input :role, as: :select, label: false, include_blank: false
    end
  end
  ...

我想要做的是更新表单以允许创建帐户和具有特定角色的成员资格的新用户。这是我迄今为止尝试过的(在与上述相同的表单块中):

f.inputs do
  f.has_many :users, heading: false, allow_destroy: true, new_record: "Add new user" do |u|
    u.input :name
    u.input :email, as: :string
    u.has_many :memberships, heading: false, allow_destroy: true, new_record: "Add membership" do |m|
      m.input :role, as: :select, label: false, include_blank: false
    end
  end
end

生成的表格:

这不起作用。如果我没有为用户的成员资格填写角色,这将“起作用”,并且成员资格模型中的before_validation 将为用户分配一个角色为Admin 的成员资格。但是,如果我尝试通过表单向用户添加角色并单击“创建帐户”,则会返回到表单,在该表单中看到一条错误消息,指出 Account must exist。这让我相信表单忽略了我嵌套在f.has_many :users 下的第二个has_many

我还尝试通过在 f.has_many :users 块中创建输入来解决此问题:

u.input :memberships, as: :select, label: "Role", include_blank: false, collection: Membership.roles

这并没有告诉我Account must exist,而是忽略我为角色分配的任何值,创建用户并为其分配一个成员身份为Admin

我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby activeadmin formtastic


    【解决方案1】:

    当您通过表单添加时,这是使用 JavaScript that includes before and after creation hooks 执行的,我没有示例,但请查看代码,看看是否有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多