ska*_*kaz 102 validation activerecord ruby-on-rails ruby-on-rails-3
我有一个模型A与另一个模型B有一个"has_many"关联.我有一个业务要求,插入A需要至少1个相关记录到B.是否有一个方法我可以调用以确保这是真的,或者我是否需要编写自定义验证?
fl0*_*00r 157
您可以使用validates_presence_of http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of
class A < ActiveRecord::Base
has_many :bs
validates_presence_of :bs
end
Run Code Online (Sandbox Code Playgroud)
或者只是validates
http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates
class A < ActiveRecord::Base
has_many :bs
validates :bs, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
但如果您将使用以下内容accepts_nested_attributes_for,则会出现错误:allow_destroy => true:嵌套模型和父级验证.在本主题中,您可以找到解决方案.
hex*_*ter 17
-------- Rails 4 ------------
简单的validates presence工作对我来说
class Profile < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
end
class User < ActiveRecord::Base
has_one :profile
end
Run Code Online (Sandbox Code Playgroud)
这样,Profile.create现在将失败.我必须user.create_profile在保存之前使用或关联用户profile.
您可以验证关联validates_existence_of(这是一个插件):
此博客条目中的示例代码段:
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :taggable, :polymorphic => true
validates_existence_of :tag, :taggable
belongs_to :user
validates_existence_of :user, :allow_nil => true
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用validates_associated.正如Faisal在答案下面的评论中指出的那样,validates_associated通过运行相关的类验证来检查相关对象是否有效.它不检查存在.值得注意的是,nil关联被认为是有效的.
如果要确保关联既存在又保证有效,还需要使用
class Transaction < ActiveRecord::Base
belongs_to :bank
validates_associated :bank
validates :bank, presence: true
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59353 次 |
| 最近记录: |