我在Rails 3.我有一個名爲Client
的模型,它有name
,phone
和email
。我的模型文件看起來像這樣:驗證始終在所有字段上都失敗
class Client < ActiveRecord::Base
belongs_to :salon
belongs_to :address
validates_presence_of :name
validates_presence_of :phone
validates_presence_of :email
accepts_nested_attributes_for :address
attr_accessible :address_attributes
end
正如你所看到的,都需要name
,phone
和email
。當我轉到可以創建新的Client
的表單並提交時,無論我在這些字段中輸入了什麼,所有三個驗證都會失敗。這裏是我的表單文件:
<%= form_for(@client) do |f| %>
<% if @client.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@client.errors.count, "error") %> prohibited this client from being saved:</h2>
<ul>
<% @client.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :salon_id, :value => Salon.logged_in_salon.id %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<%= f.fields_for :address do |address_form| %>
<div class="field">
<%= address_form.label :line1 %><br />
<%= address_form.text_field :line1 %>
</div>
<div class="field">
<%= address_form.label :line2 %><br />
<%= address_form.text_field :line2 %>
</div>
<div class="field">
<%= address_form.label :city %><br />
<%= address_form.text_field :city %>
</div>
<div class="field">
<%= address_form.label :state_id %><br />
<%= select("client[address]", "state_id", State.all.collect {|s| [ s.name, s.id ] }) %>
</div>
<div class="field">
<%= address_form.label :zip %><br />
<%= address_form.text_field :zip %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
這裏是我的create
行動:
def create
@client = Client.new(params[:client])
respond_to do |format|
if @client.save
format.html { redirect_to(@client, :notice => 'Client was successfully created.') }
format.xml { render :xml => @client, :status => :created, :location => @client }
else
format.html { render :action => "new" }
format.xml { render :xml => @client.errors, :status => :unprocessable_entity }
end
end
end
任何想法,爲什麼發生這種情況?
你能否包括你的創建動作。此外,您的表單輸出的嵌套部分? – mark
被編輯爲包含創建操作。不,嵌套部分不輸出,我不知道爲什麼。我希望這樣做,但我決定暫時不解決這個單獨的問題。 –
您需要包含一個地址實例或內聯一個實例:<%= f.fields_for @address do | address_form | %>或<%= f.fields_for @ client.build_address do | address_form | %> – mark