You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Trestle技术咨询:如何为关联关系添加内部用户新增表单

在Trestle后台表单中添加关联用户的选择新增功能

首先确保你的Show模型已配置关联和嵌套属性支持:

class Show < ApplicationRecord
  has_many :participents
  accepts_nested_attributes_for :participents, allow_destroy: true
end

接下来修改Trestle资源配置,在标签页中同时保留现有关联列表和新增表单:

Trestle.resource(:shows) do
  menu do
    item :shows, icon: "fa fa-star", group: :show_management
  end

  form do |show|
    tab :classes do
      # 展示已关联的参与用户列表
      table show.participents, admin: :participents do
        column :full_name
        actions
      end

      # 添加新增关联的嵌套表单
      nested_form :participents, build: true do |participent_form|
        # 选择已有用户进行关联(假设存在User模型)
        participent_form.select :user_id, User.pluck(:full_name, :id), prompt: "选择用户"
        
        # 若需直接创建新Participent记录,替换为对应字段输入
        # participent_form.text_field :full_name
        
        # 自动生成新增/移除操作按钮
        participent_form.actions
      end
    end
  end
end

补充说明:

  • nested_form :participents, build: true是Trestle原生嵌套表单方法,build: true会自动渲染空表单用于新增关联记录,表单将与父级Show表单同步提交,无需单独处理路由
  • 若不需要同步提交,可使用独立表单方式:
tab :classes do
  # 现有关联列表...

  panel "添加参与用户" do
    form_for [trestle, show, show.participents.new], url: trestle_admin_path(:participents, action: :create), method: :post do |f|
      f.hidden_field :show_id, value: show.id
      f.select :user_id, User.pluck(:full_name, :id), prompt: "选择用户"
      f.submit "添加", class: "btn btn-primary"
    end
  end
end

这种方式会单独提交到Participent的创建接口,适合无需与Show表单同步提交的场景。

内容的提问来源于stack exchange,提问作者user1283644

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:52:40