gpt4 book ai didi

ruby-on-rails - Rails STI和强大的参数

转载 作者:行者123 更新时间:2023-12-03 16:12:56 26 4
gpt4 key购买 nike

我有两种类型的客户资源:人员和公司。

routes.rb:

resources :clients
resources :people, :controller => "clients", :type => "Person"
resources :companies, :controller => "clients", :type => "Company"

clients_controller:
def new
@client = Client.new()
@client.type = params[:type]
end

def create
@client = current_partner.clients.new(client_params)
if @client.save
redirect_to clients_path
...
end

...
private
def client_params
params.require(:client).permit(:type, :partner_id, :name, :email, :phone, :cui, :registration_id, :address)
end

def find_client
@client ||= Client.find(params[:id])
end

client.rb
class Client < ActiveRecord::Base
validates_presence_of :type
CLIENT_TYPES = ['Person', 'Company']
end

人.rb
class Person < Client
validates_presence_of :name, :email, :phone
end

compay.rb
class Company < Client
validates_presence_of :name, :email, :cui, :registration_id, :phone
validates_uniqueness_of :cui, :registration_id, uniqueness: {scope: :partner_id}
end

问题是当我尝试编辑客户的详细信息并提交更改时,我得到了
参数缺失或值为空:客户端。
我收到此错误的路线是.../companies/3。

对这个noobie问题有帮助吗?谢谢!

最佳答案

您可以在执行许可操作之前将继承的模型伪装成其父模型

def client_params

if params.has_key? :person
params[:client] = params.delete :person
elsif params.has_key? :company
params[:client] = params.delete :company
end

params.require(:client).permit(...)

end

它只是在params哈希中重命名模型的键,就可以了。

关于ruby-on-rails - Rails STI和强大的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25281535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com