在我的應用我傳遞參數從一個控制器到另一個傳遞PARAMS滴失敗後提交
首先我創建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
。我該如何解決它?
我不知道這是否與您的問題有關,但sh如果只有一個belongs_to關聯有效(id成員不能同時擁有belongs_to和/或成員/新/成分?company_id = 9'而不是'/constituents/new.constituent?company_id=9' –