Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Iam using nested forms in rails 3.2.8 when i was go in to the edit page when ever you add the nested attributes and make it as a empty and submit the form the nested attributes was not validated and not displaying the message for these how to validates the nested attributes in nested form

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
200 views
Welcome To Ask or Share your Answers For Others

1 Answer

Let us consider your code is as follow :

User Model :

class User < ActiveRecord::Base  
  has_one :company      
  attr_accessible :first_name, :last_name     
  validates :first_name, :presence => true   
  validates :last_name, :presence => true   
  accepts_nested_attributes_for :Company   
end

User model has one company and suppose we want to accept nested attributes for users company.

Comapny Model :

class Company < ActiveRecord::Base
   belongs_to :User
   attr_accessible :company_name, :address
   validates :company_name, :presence => true
   validates :address, :presence => true
end

Comapny model has company_name and address. You can accept company attributes from user view and on user save it will check for both validates i.e. for user as well as company. If any validation fails, you will get it in user For that add following lines to your User view

<% if @user.errors.any? %>
        <div id="error_explanation">
          <div class="alert alert-error">
            The form contains <%= pluralize(@user.errors.count, "error") %>.
          </div>
          <ul>
            <% @user.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
          </ul>
        </div> 
   <% end %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...