Rails的嵌套属性会验证失败嵌套、属性、Rails

2023-09-08 15:52:36 作者:你像一场海啸

我有嵌套属性和关联验证是失败的某些原因。我不是期运用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不和它使用的构建方法,而且我认为他会与项目内置属性相关联。

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.

我也看了http://stackoverflow.com/questions/935650/acceptsnestedattributesfor-child-association-validation-failing这给我的 validates_ presence_of:除非=&GT;有效

如何得到任何想法这个工作?

Any ideas on how to get this to work?

推荐答案

validates_associated看起来是更多的麻烦比它的价值。 PROJECT_ID:如果你删除validates_ presence_of你的榜样工程。这里是一个哈克的例子,还原了验证(发现说明这里)。

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