【发布时间】:2011-01-25 17:23:58
【问题描述】:
我在 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
知道为什么会这样吗?
【问题讨论】:
-
您能否包含您的创建操作。另外,您的表单的嵌套部分是否在输出?
-
已编辑以包含创建操作。不,嵌套部分没有输出,我不知道为什么。我愿意,但我决定暂时不解决这个单独的问题。
-
您需要包含一个地址实例或构建一个内联实例: 或
-
这使得字段显示出来。谢谢。
标签: ruby-on-rails forms ruby-on-rails-3