2014-07-17 34 views
0

在我的應用我傳遞參數從一個控制器到另一個傳遞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_identrepreneur_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 

的問題是我在鏈接中傳遞的參數在下降失敗後嘗試以節省@constituentcompany_identrepreneur_idnil。我該如何解決它?

+0

我不知道這是否與您的問題有關,但sh如果只有一個belongs_to關聯有效(id成員不能同時擁有belongs_to和/或成員/新/成分?company_id = 9'而不是'/constituents/new.constituent?company_id=9' –

回答

0

發生這種情況是因爲在您提交表單後,不再有params[:company_id] = 9。在render :new完成後,您將有params[:constituent][:company_id] = 9

因此,要解決這個問題,你需要發送的不是這個get請求新的制憲:

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] 
+0

填充),最好使用多態關聯。 – vladra