即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

嵌套属性的验证

栈溢出 chandra sekhar 16℃ 0评论
本文目录
[隐藏]

1.原始问题:Validation for nested attributes

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

2.被采纳答案

暂无被采纳答案,请参照下面其他答案。

3.其他高票答案

3.1.第1个答案

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? %>
        
The form contains <%= pluralize(@user.errors.count, "error") %>.
    <% @user.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %>

转载请注明:CodingBlog » 嵌套属性的验证

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情