Is there a way for a database to only allow one row (e.g. for site-wide settings) ?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With