0

Hi i want to insert customer name in one table by using customer id insert customer city in other table. my code inserts only customer. the cities are not inserting

my console

Started POST "/pages" for 127.0.0.1 at 2017-01-30 14:40:15 +0530 Processing by PagesController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"NfyA8PpA4wZIAOPX7fYstwvt2suXoTYgl9ep1M6yTSh6ZPX8lt+oOfPX6sFXGOuxTidVND6qaksz6iZ2enGj9g==", "customer"=>{"name"=>"fgfg", "custcity"=>{"cityname"=>"2fg"}}, "commit"=>"submit"} Unpermitted parameter: custcity (0.1ms) begin transaction SQL (2.3ms) INSERT INTO "customers" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "fgfg"], ["created_at", 2017-01-30 09:10:15 UTC], ["updated_at", 2017-01-30 09:10:15 UTC]] (231.7ms) commit transaction (0.2ms) begin transaction (0.1ms) rollback transaction Redirected to http://localhost:3000/pages Completed 302 Found in 247ms (ActiveRecord: 234.3ms)

new.html.erb

<%= form_for @customer, url: {action: "create"} do |f| %>
<%= label_tag("Customer") %>
<br>
<%= f.text_field(:name) %>
<br>
<%= f.fields_for @custcity do |c| %>
        <%= label_tag("City 1") %>
        <br>
        <%= c.text_field(:cityname) %>
        <br>
        <%= label_tag("City 2") %>
        <br>
        <%= c.text_field(:cityname) %>
        <br>
<% end %>
<br>
<%= f.submit("submit") %>
<% end %>

pages_controller.rb

  def create
    @customer = Customer.new(cust_params)
    if @customer.save
       session[:customer_id] = @customer.id

      #@custcity = Custcity.create(cityname: params[:customer][:cityname], cust_id: session[:customer_id])
      @custcity = Custcity.create({cityname: params[:customer][:cityname], cust_id: @customer.id})
      #@custcity.save
      redirect_to pages_path
    else
      redirect_to new_page_path
    end
  end

  private
  def cust_params
    params.require(:customer).permit(:name, :custcity => [])
  end
end
1
  • You should use strong nested parameters and define customer city params in strong parameter. Commented Jan 30, 2017 at 9:39

1 Answer 1

1

Wrong path to :cityname key. You've lost :custcity

@custcity = Custcity.create({cityname: params[:customer][:custcity][:cityname], cust_id: @customer.id})

Permit cityname too:

params.require(:customer).permit(:name, :custcity => [:cityname])
Sign up to request clarification or add additional context in comments.

1 Comment

By idea, Customer and Custcity models should be linked with has_many association and you don't need to call Custcity.create manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.