Pavel
Pavel

Reputation: 1974

create action: Couldn't find object without an ID

I'm trying to create obeject in controller and I pass parameter from hidden_field to find parent object

controller:

      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

My logs indicate that entrepreneur_id is passed:

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

But I get an error Couldn't find Entrepreneur without an ID

What should I fix in my code? Thanks!

Upvotes: 0

Views: 135

Answers (1)

Pavel
Pavel

Reputation: 1974

Referring to Ruby Racer comment I find the answer.

In controller create action I needed to rewrite building object like:

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

Upvotes: 1

Related Questions