Validating elements of a `has_many` relationship on save

Hello,

I’m trying to validate the elements of a has_many relationship on create

class Request
  has_many :elements

  validate :elements_condition, on: :create 

  def elements_condition
    x = elements.joins(SomeOtherTable.scope).all?(&:condition?)

    # if !x errors.add(:base, [...]
  end
end

But when I build a request, and it’s not persisted yet, the elements in elements.join will launch a query where (elements.request_id = NULL) because it tries to fetch them, and the query is not persisted, hence NULL.

How do I say: look at the variable you’ve got instead rather than the actual query which will always return no result?

You’ve correctly identified the problem: joins won’t work unless the objects in question are persisted.

In the elements_condition method, I would iterate over elements and de-reference the SomeOtherTable association like this:

   unless elements.find{ |e| e.some_other_table.scope.all?(&:condition?) }
      errors.add(:base, [...]) 
    end
1 Like