0
假设我有ParentModel
has_many ChildModel
。Rails验证 - 在创建子模型时验证父模型
有没有一种方法来检查(验证)ParentModel
而创建子(例如像检查是否具有相同名称的子记录存在?
假设我有ParentModel
has_many ChildModel
。Rails验证 - 在创建子模型时验证父模型
有没有一种方法来检查(验证)ParentModel
而创建子(例如像检查是否具有相同名称的子记录存在?
这是非常简单的,如有错误指正。
def Parent
has_many :children
end
def Child
belongs_to :parent
#Here you could run some validations, for example:
validates :name,presence: true, length: { minimum: 1 },uniqueness: { scope: :parent_id }
#by running uniqueness with scope, you can repeat names, but not associated with the same parent.
end
那么可以,例如:
p = Parent.first #suppose we already have the parent
p.child.new #create a child, with attributes if needed
p.valid? #p won't be valid unless his new child is
替代:
p = Parent.first #suppose we already have the parent
c = Child.new #create a child, with attributes if needed
p.children << C#append the child to the collection, if C is invalid, then it won't be saved into the database
p.valid? #validate,
您的解决方案非常简单。我最终创建了一个自定义方法,并使用'self'访问创建的(尚未保存的)子项的父项 – Ancinek
所以这听起来像你可能正在寻找一个复合独特的索引?在特定的字段和外键上? – axlj
如果验证应该只检查名称唯一性,但是它必须稍微复杂一些,所以我想定义一个方法并将其用于验证 – Ancinek
也许这个问题会有所帮助:http:// stackoverflow。 com/questions/11849179/rails-validation-an-attribute-based-on-another-model – axlj