Ruby on rails 如何使用rails确保数据库中的单个条目?
我已经为Ruby on rails 如何使用rails确保数据库中的单个条目?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我已经为特色文章创建了一个表格,其中有许多文章,以便在网站首页保留特色文章。现在我想确保我在特色文章中只创建了一个条目。寻找可以存储在数据库中的类似于单例模型条目的内容。什么是rails确保这一点的方法 由于这将是一个单条目表,我认为我的数据库开销将是巨大的,有没有更好的方法来存储这种类型的单条目?您可以通过执行以下操作来实现这一点: 特写帖子\u controller.rb def new if featured_post.empty? # create feature
特色文章
创建了一个表格,其中有许多
文章
,以便在网站首页保留特色文章。现在我想确保我在特色文章
中只创建了一个条目。寻找可以存储在数据库中的类似于单例模型条目的内容。什么是rails
确保这一点的方法
由于这将是一个单条目表,我认为我的数据库开销将是巨大的,有没有更好的方法来存储这种类型的单条目?您可以通过执行以下操作来实现这一点: 特写帖子\u controller.rb
def new
if featured_post.empty?
# create featured_posts
else
redirect_to featured_posts_path
# or you can throw an error
end
end
另一种方法是确保没有人可以访问new and create方法:
def FeaturedPostsController < ApplicationController
before_action :check_post_presence, only: [:new, :create]
private
def check_post_presence
redirect_to featured_posts_path if featured_post.exists?
end
end
我这样做的方法是,在posts表和我的验证器中只包含一个is_特征的布尔列,确保只有一个列的值为true,例如:
class model < ActiveRecord::Model
validate :validate, on: :create
def validate(record)
errors.add('Maximum of one featured post') unless model.find(:is_featured => true).length == 1
end
类模型true)。长度==1
结束
我这样做的方法是,在您的posts表和我的验证器中只包含一个具有is_特征的布尔列,确保只有一个列的值为true。@hd1谢谢,我正在删除此表。另外,为了消除计算null的麻烦,例如,如果您想获取与true相反的值,建议通过迁移此布尔值在数据库级别将默认值设置为false
class model < ActiveRecord::Model
validate :validate, on: :create
def validate(record)
errors.add('Maximum of one featured post') unless model.find(:is_featured => true).length == 1
end