【问题标题】:Validation always fails on all fields所有字段的验证总是失败
【发布时间】:2011-01-25 17:23:58
【问题描述】:

我在 Rails 3 上。我有一个名为 Client 的模型,它有 namephoneemail。我的模型文件如下所示:

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

如您所见,namephoneemail 都是必需的。当我转到应该能够创建一个新的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


【解决方案1】:

这是因为您将:address_attributes 设置为唯一可访问的属性。改变

attr_accessible :address_attributes

attr_accessible :address_attributes, :name, :phone, :email

或者不要使用批量分配。

【讨论】:

猜你喜欢
  • 2015-04-04
  • 2014-03-29
  • 2016-01-18
  • 2016-03-25
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 2023-01-04
相关资源
最近更新 更多