Only one model instance in Rails

I am working on my first Rails application. It should store some information about one advertisement that will be displayed on each page. The administrator simply needs to be able to set the URL, title and image. Obviously, I only need one instance of this advertising object.

I created a model that inherits from ActiveRecod :: Base, but this seems incorrect because it is configured to store multiple declarations in the database table.

What is the best way for me to do this? What should the model and controller look like?

Thanks in advance, Avi

+3
source share
4 answers

, ActiveRecord, boolean, , . .

, . :

  • false
  • 0 true.
  • , true.

class Ad < ActiveRecord::Base

  named_scope :has_active, :conditions => {:active => true}

  def validate
    errors.add_to_base "You can only have one active advertisement" 
        unless self.active_flag_valid?
  end

  def active_flag_valid?
    self.active == false || 
    Ad.has_active.size == 0 || 
    ( Ad.has_active.size == 1 && !self.active_changed?)
  end
end
+1

, (URL, , ) , , AR - . , , .

, ? , - , , .

+2

. , . , Rails created_at updated_at , / - .

+1

A better way would be to add a check that checks to see if one record exists.

Inside your model:

validate :check_record, on: :create #please not that validate in this case is singular

def check_record
 if Ad.all.count === 1
   errors[:base] << "You can only have one active advertisement"
 end
end
+1
source

Source: https://habr.com/ru/post/1716350/


All Articles