0

Building a validator that has to check multiple siblings who belong to the same (option) parent.

class Optionrate < ActiveRecord::Base
  belongs_to :option

  attr_accessible :from, :to, :option_id

  validates_presence_of :from, :to

  validate :not_overlap

  scope :overlaps, ->(from, to) do
    where "((from <= ?) and (to >= ?))", to, from
  end

  def overlaps?
    overlaps.exists?
  end

  def overlaps
    siblings.overlaps from, to
  end

  def not_overlap
    errors.add(:key, t('overlap_message')) if overlaps?
  end

  def siblings
    Optionrate.where('option_id = ?', option_id).all
  end

is generating an error: "undefined method `overlaps' for []:Array" referring to statement

siblings.overlaps from, to

The fact that siblings is plural makes me assume it is expecting an array, so that's an oddity.

[Another was that the where statement was not accepting *where('option_id = ?', params[:option_id])* whence the record has yet to be created as the validation has not completed]

Jerome
  • 5,583
  • 3
  • 33
  • 76

1 Answers1

1

Please try to run the code after removing .all from Optionrate.where('option_id = ?', option_id).all because when you are using .Where then there is no need to use .all method.

Or

Take a look on following url for reference http://guides.rubyonrails.org/3_2_release_notes.html#active-record

Amit Sharma
  • 3,427
  • 2
  • 15
  • 20
  • Yes, you and phoet hit the issue on its head. Now, the translations key cannot take the i18n helper method t(). Only 'overlap_message' runs. Digging through that one! – Jerome Feb 28 '14 at 08:07
  • try this `errors.add(:key, I18n.t :overlap_message) if overlaps?` i hope you have **overlap_message** key in translation files. – Amit Sharma Feb 28 '14 at 09:15