在我的应用中,我将参数从一个控制器传递到另一个控制器
首先我创建Company
对象并在重定向链接中传递其id
参数
companies_controller:
class CompaniesController < ApplicationController
def new
@company = Company.new
end
def create
@company = current_user.companies.build(company_params)
if @company.save
redirect_to new_constituent_path(:constituent, company_id: @company.id)
else
render 'new'
end
end
private
def company_params
params.require(:company).permit(:name)
end
end
成功Company
保存后,我被重定向到创建Constituent
对象。我使用链接company_id
中传递的参数填充entrepreneur_id
或http://localhost:3000/constituents/new.constituent?company_id=9
,例如
成分/新:
= simple_form_for @constituent do |f|
= f.input :employees
- if params[:entrepreneur_id]
= f.hidden_field :entrepreneur_id, value: params[:entrepreneur_id]
- elsif params[:company_id]
= f.hidden_field :company_id, value: params[:company_id]
= f.button :submit
constituents_controller:
class ConstituentsController < ApplicationController
def new
@constituent = Constituent.new
end
def create
@constituent = Constituent.create(constituent_params)
if @constituent.save
redirect_to root_url
else
render 'new'
end
end
private
def constituent_params
params.require(:constituent).permit(:employees, :company_id, :entrepreneur_id)
end
end
问题是我在链接中传递的参数在尝试保存@constituent
失败并且company_id
或entrepreneur_id
为nil
后失败。我该如何解决?
答案 0 :(得分:0)
这是因为在您提交表单后,不再有params[:company_id] = 9
。 render :new
完成后,您将获得params[:constituent][:company_id] = 9
。
因此,要解决此问题,您需要将此get请求发送给新的Constituent:
http://localhost:3000/constituents/new?company_id=9
但是这样的事情:
http://localhost:3000/constituents/new?constituent[company_id]=9
如果params[:constituent]
不存在,为了避免错误,您的观点会变得更加丑陋:
- if params[:constituent]
- if params[:constituent][:entrepreneur_id]
= f.hidden_field :entrepreneur_id, value: params[:constituent][:entrepreneur_id]
- elsif params[:constituent][:company_id]
= f.hidden_field :company_id, value: params[constituent][:company_id]