bourg-ismael
bourg-ismael

Reputation: 93

Rails 4 : Access attributes from model

I have a Model Reservation with 2 columns, user_id and teleporter_id.

I want to lock the creation of a Reservation to 3 same teleporter_id but I don't know how to access to the attribute teleporter_id from the Model that I'm creation.

Here my code :

class Reservation < ActiveRecord::Base
  # Relations
  belongs_to :teleporter
  belongs_to :user

  # Validations
  validate :max_reservation

  def max_reservation
    if Reservation.where(:teleporter_id => self.teleporter_id).count >= 3
      errors.add(:base, t('reservation.model.error.max_reservation'))
    end
  end
end

I think that the problem is from self.teleporter_id but I don't know how access to the attribut teleporter_id from the current model.

Upvotes: 0

Views: 263

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

Try this:

def max_reservation
  _id = self.teleporter_id
  errors.add(:base, t('reservation.model.error.max_reservation')) unless Reservation.where(teleporter_id: _id).count <= 3
end

Upvotes: 1

Related Questions