繁体   English   中英

如何在rails中使用form_with和self join?

[英]How to use form_with with self join in rails?

我有一个User model 可以有多个子帐户。 我已经如下设置了 model

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 从 model class 中推断出 url,因为它们都是用户。 它推断出的路径user_user_path而不是user_child_accounts_path

那么,是否有一种使用自连接创建 forms 的轨道方式? 还是我手动处理了这种情况?

首先你有一个复数错误:

resources :users do
  resources :child_accounts 
end

resource用于声明 奇异资源

但是无论如何, 多态路由助手将无法自动路由到该路径,当您将 model 实例传递给form_forform_withlink_tobutton_to他们通过调用#model_name并使用ActiveModel::Naming的方法来推断路由助手方法的名称. 由于@child_account是 User 的一个实例,因此您将获得user_users_path 多态路由助手不知道您的关联。

如果您使用form_forform_with在这里根本没有关系,因为两者都使用完全相同的方法来找出 model 或模型数组的路径。

您要么需要明确传递 url:

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

或者使用单表 inheritance

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM