ruby-on-rails - 向模型添加验证
问题描述
我想为我的 Rails 应用程序添加一些验证。我正在使用 Postgresql。我创建了一个 post 表和一个 user 表。每个用户可以有多个帖子,每个帖子可以有多个用户。但是,每个帖子只能有一个类别(另一个表)。我需要在模型中添加什么?
解决方案
你应该能够做到,简单地说:
# == 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
推荐阅读
- python - 使用 Boto3 列出所有“活动”EMR 集群
- python - 如何/如何使用 python 和密码模块生成 PKCS#12 文件?
- java - 我的代码中的 For 循环失败。根本不执行
- javascript - 在javascript中等待获取结果
- javascript - JSX 在 React 中解析但不解析依赖(webpack,babel)
- python - bulk_insert 不会将值插入可空字段
- java - 检查是否在 URL 中指定了参数
- python - 如何在 pycairo 中快速绘制大量多边形?
- ruby - 我可以在类中包含模块方法吗?
- r - R中str_detect函数中的字边界