数据库是否只允许一行(例如,用于站点范围的设置)?
答案 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)
这一行中只有一列吗?如果没有,则添加具有迁移的新列可能会过度。您至少可以使此表包含“名称”和“值”列,并按名称上的唯一性进行验证。