Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Database with just one row

Is there a way for a database to only allow one row (e.g. for site-wide settings) ?

like image 953
Yo Ludke Avatar asked Jan 18 '13 16:01

Yo Ludke


2 Answers

class Whatever < ActiveRecord::Base
  validate :there_can_only_be_one

  private

  def there_can_only_be_one
    errors.add_to_base('There can only be one') if Whatever.count > 0
  end
end
like image 153
Unixmonkey Avatar answered Oct 05 '22 23:10

Unixmonkey


In Rails 4:

class Anything < ActiveRecord::Base
  before_create :only_one_row

  private
  def only_one_row
    false if Anything.count > 0
  end
end

Silent errors are bad, then

class Anything < ActiveRecord::Base
  before_create :only_one_row

  private
  def only_one_row
    raise "You can create only one row of this table" if Anything.count > 0
  end
end
like image 44
macabeus Avatar answered Oct 05 '22 23:10

macabeus