Rails ActiveRecord数据库只有一行

时间:2013-01-18 16:29:07

标签: mysql ruby-on-rails rails-activerecord

数据库是否只允许一行(例如,用于站点范围的设置)?

3 个答案:

答案 0 :(得分:6)

class Whatever < ActiveRecord::Base
  validates :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

答案 1 :(得分:3)

在Rails 4中:

class Anything < ActiveRecord::Base
  before_create :only_one_row

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

无声错误很糟糕,然后

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

答案 2 :(得分:2)

这一行中只有一列吗?如果没有,则添加具有迁移的新列可能会过度。您至少可以使此表包含“名称”和“值”列,并按名称上的唯一性进行验证。