针对has_many关联的Rails验证

Anu*_*rag 4 validation ruby-on-rails has-many

我在孩子存在的has_many关系上遇到验证时遇到问题,但父母却没有.但是,在创建/保存父对象时,我想确保已保存特定的子级(具有某些属性).

Parent对象有一个对象has_many Child.该Child对象持久化到数据库第一,因而不必父任何引用.关联结构是:

Parent
  - has_many :children 

Child
  - someProperty: string
  - belongs_to: parent
Run Code Online (Sandbox Code Playgroud)

例如,有三个子对象:

#1 {someProperty: "bookmark", parent: nil}
#2 {someProperty: "history", parent: nil }
#2 {someProperty: "window", parent: nil }
Run Code Online (Sandbox Code Playgroud)

仅当父项包含具有someProperty history和的子对象时,父项才有效window.

我在控制器中设置父节点:

p = Parent.new(params[:data])
for type in %w[bookmark_id history_id window_id]
    if !params[type].blank?
        p.children << Child.find(params[type])
    end
end
// save the parent object p now
p.save!
Run Code Online (Sandbox Code Playgroud)

当子项被分配给父项时<<,它们不会立即保存,因为父项的ID不存在.为了保存父母,它必须至少有这2个孩子.我怎么能解决这个问题?欢迎任何输入.

Mil*_*ota 5

不知道为什么你需要做这样的事情,但无论如何,这样做怎么样?

class Parent < ActiveRecord::Base

  CHILDREN_TYPES = %w[bookmark_id history_id window_id]
  CHILDREN_TYPES.each{ |c| attr_accessor c }

  has_many :children

  before_validation :assign_children
  validate :ensure_has_proper_children

private

  def assign_children
    CHILDREN_TYPES.each do |t|
      children << Child.find(send(t)) unless send(t).blank?
    end
  end

  def ensure_has_proper_children
    # Test if the potential children meet the criteria and add errors to :base if they don't
  end
end
Run Code Online (Sandbox Code Playgroud)

控制器:

...
p = Parent.new(params[:data])
p.save!
...
Run Code Online (Sandbox Code Playgroud)

如您所见,我首先将所有逻辑移至模型.然后,有两个步骤来拯救孩子.首先,我们将子项分配给父项,然后验证它们是否符合所需条件(在那里插入逻辑).

抱歉做空.如有必要,我会回答任何进一步的问题.