我在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