0
votes

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.Jyoti mishra

1 Answers

1
votes

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])