Rails 5嵌套属性不保存

时间:2017-01-09 03:39:45

标签: ruby-on-rails

我有一个地址和客户模型,想要以1种形式创建与关联客户的地址。 ' ADDRESS_ID'是Address表的主键,是Customer表的外键。

address.rb

has_one :customer
accepts_nested_attributes_for :customer

customer.rb

belongs_to :address

的routes.rb

namespace :admin do
  resources :customers, :addresses
end

管理员\地址\新

<%= form_for [:admin, @address] do |a| %>
  <p>Customer</p>
    <%= a.fields_for @customer do |c| %>
    <%= c.text_field :first_name %>
    <%= c.text_field :last_name %>
    <%= c.select(:store_id, 1..2) %>
    <% end %>

  <p>Address</p>
    <%= a.text_field :phone %>
    <%= a.text_field :address %>
    <%= a.text_field :address2 %>
    <%= a.text_field :district %>
    <%= a.number_field :city_id %></td>
    <%= a.text_field :postal_code %>
<%= a.submit %>
<% end %>

addresses_controller.rb

class Admin::AddressesController < ApplicationController

def new
  @address = Address.new
  @customer = Customer.new
end

def create
  @address = Address.new(address_params)
  if @address.save
    redirect_to(admin_customers_path)
  else
    render('new')
  end   
 end

private
  def address_params
    params.require(:address).permit(:address, :address2, :district, :city_id, :postal_code, :phone, 
     customer_attributes: [:first_name, :last_name, :store_id, :address_id])
  end

它正在创建地址,但返回“未经许可的参数:客户&#39;在rails服务器中:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"T49t....", 
"address"=>{"customer"=>{"first_name"=>"Aaron", "last_name"=>"Thomas", "store_id"=>"2"}, 
"phone"=>"4151101010", "address"=>"10 Test st", "address2"=>"", "district"=>"Soma", "city_id"=>"15", "postal_code"=>"94103"}, "commit"=>"Create Address"}
Unpermitted parameter: customer
  (0.0ms)  BEGIN
  SQL (8.9ms)  INSERT INTO `address` (`address`, `address2`, `district`, `city_id`, `postal_code`, `phone`) VALUES ('10 Test st', '', 'Soma', 15, '94103', '4151101010')
  (51.5ms)  COMMIT
Redirected to http://localhost:3000/admin/customers

谢谢。

0 个答案:

没有答案