2014-07-17 85 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