首页 > 解决方案 > 如何在rails中使用form_with和self join?

问题描述

我有一个User模型可以有很多子帐户。我已将模型设置如下

class User < ApplicationRecord
  has_many :child_accounts, class_name: "User", foreign_key: "parent_account_id"
  belongs_to :parent_account, class_name: "User", optional: true
end

我创建了一个ChildAccountsController来处理子帐户创建等,并定义了如下路线。

resources :users do
  resource :child_accounts
end

但我可以form_with在这种情况下开始工作。作为

form_with(model: [current_user, @child_account], local: true) do
#...
end 

form_with 从模型类中推断出 url,因为它们都是用户。它推断的路径user_user_path而不是user_child_accounts_path.

那么,有没有一种 Rails 方法可以创建带有自连接的表单?还是我手动处理了这种情况?

标签: ruby-on-railsruby

解决方案


首先你有一个复数错误:

resources :users do
  resources :child_accounts 
end

resource用于声明奇异资源

但是无论如何,当您将模型实例传递给,时,多态路由助手将无法自动路由到该路径,并且它们通过调用和使用 的方法推断出路由助手方法的名称。因为是 User 你得到的一个实例。多态路由助手不知道您的关联。form_forform_withlink_tobutton_to#model_nameActiveModel::Naming@child_accountuser_users_path

form_for如果您使用或form_with两者都使用完全相同的方法从模型或模型数组中找出路径,那么这里根本没有关系。

您要么需要显式传递 url:

form_with(model: @child_account, url: user_child_accounts_path(current_user), local: true) do
#...
end

或者使用单表继承

class AddTypeToUsers < ActiveRecord::Migration[6.0]
  def change
    change_table :users do |t|
      t.string :type
    end
  end
end
class User < ApplicationRecord
  has_many :child_accounts, 
    foreign_key: "parent_account_id",
    inverse_of: :parent_account
end

class ChildAccount < User
  belongs_to :parent_account, 
    class_name: "User",
    inverse_of: :child_accounts
end
class ChildAccountsController < ApplicationController
  def new
    @child_account = current_user.child_accounts.new
  end

  def create
    @child_account = current_user.child_accounts.new(child_account_params)
    # ...
  end

  private
  def child_account_params
    params.require(:child_account)
          .permit(:foo, :bar, :baz)
  end
end

推荐阅读