create action:找不到没有ID的对象

时间:2014-07-01 22:53:44

标签: ruby-on-rails ruby-on-rails-4

我试图在控制器中创建obeject并从hidden_field传递参数以查找父对象

控制器:

      def new
        @address = Address.new
      end

      def create
        @address = Entrepreneur.find(params[:entrepreneur_id]).addresses.build(address_params)
        if @address.save
          redirect_to root_url
        else
          render 'new'
        end
      end

      private

      def address_params
        params.require(:address).permit(:region, :city, :street, :house, :building, :office)
      end

new.html.haml:

= simple_form_for @address do |f|
  = f.input :region
  =f.input :city
  =f.input :street
  =f.input :house
  =f.input :building
  =f.input :office
  = f.hidden_field :entrepreneur_id, :value => 9 # 9 is for example
  =f.submit

我的日志表明corporateur_id已通过:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"ea+Vb8JA4IH4AYm4odDMvSGFJiHetR6YDDk2AH8rCmE=", "address"=>{"region"=>"", "city"=>"", "street"=>"", "house"=>"", "building"=>"", "office"=>"", "entrepreneur_id"=>"9"}, "commit"=>"Create Address"}

但我收到错误Couldn't find Entrepreneur without an ID

我的代码应该修复什么?谢谢!

1 个答案:

答案 0 :(得分:1)

参考Ruby Racer评论,我找到答案。

在控制器create操作中,我需要重写构建对象,如:

@address = Entrepreneur.find(params[:address][:entrepreneur_id]).addresses.build(address_params)