找到你要的答案

Q:How to ensure single entry in database with rails?

Q:如何确保数据库中的单输入与Rails?

I have created a table for featured_posts, which has_many posts to keep featured posts in the front page of the website. Now I want to ensure that I am creating only one entry at featured_posts. Looking for something like singleton model entry that can be stored in database. What is rails way to ensure that?

Since this is going to be an one entry table, I think my database overhead will be huge, is there any better way to store this type of single entry?

我创建了一个表,featured_posts,has_many岗位保持精选发布在网站的首页。现在我要确保我在featured_posts创建只有一个入口。寻找可以存储在数据库中的单例模型条目。什么是Rails的方式来保证?

由于这将是一个入口表,我认为我的数据库开销将是巨大的,有没有更好的方法来存储这种类型的单入口?

answer1: 回答1:

The way I'd do this is to just have an is_featured boolean column in your posts table and in my validator, ensure there's only one with this as true -- for example:

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

我这样做是为了你的职位表和我的验证器有is_featured布尔列,确保只有一个这是真实的--例如:

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
answer2: 回答2:

You can achieve this by doing the following:

featured_posts_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

Another way is to ensure that no one can access the new and create method:

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

Finally you can create a default featured post on seed and remove the new and create method altogether by adding the data in db/seeds.rb:

featured_post = FeaturedPost.create title: "Default Posts"

你可以做到以下几点:

featured_posts_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

另一种方法是确保没有人可以访问新的和创建方法:

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

最后,你可以创建一个默认的精选后的种子和删除新创建的方法完全在db/seeds.rb添加数据:

featured_post = FeaturedPost.create title: "Default Posts"
ruby-on-rails  ruby