首页 > 解决方案 > 向模型添加验证

问题描述

我想为我的 Rails 应用程序添加一些验证。我正在使用 Postgresql。我创建了一个 post 表和一个 user 表。每个用户可以有多个帖子,每个帖子可以有多个用户。但是,每个帖子只能有一个类别(另一个表)。我需要在模型中添加什么?

标签: ruby-on-railspostgresql

解决方案


你应该能够做到,简单地说:

# == Schema Information
#
# Table name: posts
#
#  id               :integer          not null, primary key
#  category_id      :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class Post < ApplicationRecord
  belongs_to :category
end

...和...

# == Schema Information
#
# Table name: categories
#
#  id               :integer          not null, primary key
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class Category < ApplicationRecord
  has_many :posts
end    

因为您使用的是 rails 6,belongs_to所以将强制存在有效的category_id. 无需进一步验证。如果您想category_id成为可选的,请执行以下操作:

# == Schema Information
#
# Table name: posts
#
#  id               :integer          not null, primary key
#  category_id      :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class Post < ApplicationRecord
  belongs_to :category, optional: true
end

推荐阅读