ruby-on-rails - 如何在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 方法可以创建带有自连接的表单?还是我手动处理了这种情况?
解决方案
首先你有一个复数错误:
resources :users do
resources :child_accounts
end
resource
用于声明奇异资源。
但是无论如何,当您将模型实例传递给,时,多态路由助手将无法自动路由到该路径,并且它们通过调用和使用 的方法推断出路由助手方法的名称。因为是 User 你得到的一个实例。多态路由助手不知道您的关联。form_for
form_with
link_to
button_to
#model_name
ActiveModel::Naming
@child_account
user_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
推荐阅读
- javascript - php可以在响应ajax请求之前等待很长时间吗
- c# - 寻求 C# ASP.NET Core Web App 项目的帮助
- docker - 在 docker 上等待用户输入 golang cli app
- css - 针对移动设备的 GridView CSS 更改
- javascript - 如何将图像的响应高度或宽度添加到容器中?
- azure - Azure CDN 规则引擎将 www 添加到裸域
- javascript - 尝试使用 React-Router-Dom 时出现问题
- javascript - 将 div 移动到另一个 div
- django - 没有错误消息,使用 slug 和 get_absolut_url() 重定向到 DetailView
- angular - SwaggerUI windows 身份验证流程