开发者

Validation always fails on all fields

I'm on Rails 3. I have a model called Client that has name, phone and email. My model file looks like this:

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

As you can see, name, phone and email are all required. When I go to the form where I'm supposed to be able to create a new Client and submit it, all three validations fail, no matter what I put in the fields. Here is my form file:

<%= 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 %>

Here's my create 开发者_JS百科action:

  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

Any idea why this is happening?


It's because you set :address_attributes as the only accessible attribute. Change

attr_accessible :address_attributes

to

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

or don't use mass assignment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜