Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause and model function in Rails

Here is my model:

class Ad < ActiveRecord::Base
  attr_accessor :current
  has_attached_file :image
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  def current
    true unless Time.now>self.expires_on
  end
end

Then I am trying this:

Ad.where(location: "Dispenser Show Sidebar Left", current: true)

Here is the error:

Unknown column 'ads.current' in 'where clause'

How can I call current in the where clause?

like image 988
Abram Avatar asked Dec 31 '25 08:12

Abram


1 Answers

Convert your current method into a scope:

class Ad < ActiveRecord::Base
  attr_accessor :current
  has_attached_file :image
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  scope :current, -> {
    where(['expires_on < ?', Time.now])
  }
end

And then chain it to the where conditions

Ad.where(location: "Dispenser Show Sidebar Left").current
like image 174
infused Avatar answered Jan 02 '26 02:01

infused