Rails 嵌套属性关联验证失败 [英] Rails Nested Attributes Association Validation Failing
问题描述
我为 Rails 模型嵌套了属性,但由于某种原因关联验证失败.我没有使用 accepts_nested_attributes_for,但我正在做一些非常相似的事情.
I have nested attributes for a Rails model and the associations validations are failing for some reason. I am not useing accepts_nested_attributes_for, but I am doing something very similar.
class Project < ActiveRecord::Base
has_many :project_attributes
def name
project_attributes.find_by_name("name")
end
def name=(val)
attribute = project_attributes.find_by_name("name")
if attribute
attribute.value = val
else
project_attributes.build(:name=>"name", :value=>val)
end
end
end
class ProjectAttribute < ActiveRecord::Base
belongs_to :project
validates_presence_of :name
validates_uniqueness_of :name, :scope => :project_id
validates_presence_of :project_id, :unless => lambda {|attribute| attribute.project.try(:valid?)}
validates_associated :project
end
这是一个人为的例子,但类似于我想要做的.我查看了 accepts_nested_attributes_for 的作用,它使用了 build 方法,我认为该方法会将构建的属性与项目相关联.
This is a contrived example, but similar to what I am trying to do. I've taken a look at what accepts_nested_attributes_for does and it uses the build method, which I thought would associate the built attribute with the project.
我还查看了 accepts_nested_attributes_for 子关联验证失败,它给了我 validates_presence_of :unless=>valid?
I also looked at accepts_nested_attributes_for child association validation failing which gave me the validates_presence_of :unless=>valid?
关于如何让它发挥作用的任何想法?
Any ideas on how to get this to work?
推荐答案
validates_related 看起来比它的价值更麻烦.如果您删除 validates_presence_of :project_id,则您的示例有效.这是一个恢复验证的 hacky 示例(找到描述 这里).
validates_associated looks to be more trouble than it's worth. Your example works if you drop validates_presence_of :project_id. Here is a hacky example that restores that validations (found description here).
class ProjectAttribute < ActiveRecord::Base
belongs_to :project
validates_presence_of :name
validates_uniqueness_of :name, :scope => :project_id
validates_presence_of :project_id, :unless => Proc.new { |project_attribute|
project = project_attribute.project
ObjectSpace.each_object(Project) {|o| project = o if o.project_attributes.include?(project_attribute)} unless project
project
}
end
这篇关于Rails 嵌套属性关联验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!