在Rails中出现Has_one Assosiation错误

时间:2015-05-24 19:36:43

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

我有供应商与地址的一对一关系,并在我的供应商表中存储地址的外键。

SuppliersController

def new
 @supplier = Supplier.new
 @address  =@supplier.build_address
end
def create
 @supplier = Supplier.new(supplier_params)
 respond_to do |format|
   if @supplier.save 
     format.html { redirect_to @supplier, notice: 'Supplier was    successfully created.' }
    format.json { render :show, status: :created, location: @supplier }
  else
    format.html { render :new }
    format.json { render json: @supplier.errors, status: :unprocessable_entity }  
  end
end

end
private
# Never trust parameters from the scary internet, only allow the white    list through.
def supplier_params
  params[:supplier].permit(:name,addresses:
    [:city,:state,:country,:address])
end

模型

class Supplier < ActiveRecord::Base
belongs_to :address
accepts_nested_attributes_for :address, allow_destroy: true
end

Address < ActiveRecord::Base
    has_one :supplier
end

Parameters:{"utf8"=>"✓","authenticity_token"=>"IhRtHitlZqaOAD7HULiMnWn4Hfqwe++zpBJjRceitplJPy5VcmCRlnp9QNJuZwaXhK1g2mvHMpNtfSjRGVPKuw==","supplier"=>{"name"=>"k ","addresses"=>{"city"=>"k","state"=>"k","country"=>"k","address"=>"k"}},"commit"=>"Create Supplier"}

查看

enter code here

<%= form_for(@supplier) do |f| %>
<% if @supplier.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@supplier.errors.count, "error") %> prohibited this supplier from being saved:</h2>

<ul>
<% @supplier.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
enter code here
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<h2>Adrress</h2>


<%= f.fields_for :addresses do |address_fields| %>

<div class="field">
city  : <%= address_fields.text_field :city %>
</div>
<div class="field">
<%= address_fields.label :state %><br>
<%= address_fields.text_field :state %>
</div>
<div class="field">
<%= address_fields.label :country %><br>
<%= address_fields.text_field :country %>
</div>
<div class="field">
<%= address_fields.label :address %><br>
<%= address_fields.text_field :address %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

0 个答案:

没有答案