我需要确保产品在创建时至少有一个类别.

class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, :through => :product_categories #must have at least 1
end

class Category < ActiveRecord::Base
  has_many :product_categories
  has_many :products, :through => :product_categories
end

class ProductCategory < ActiveRecord::Base
  belongs_to :product
  belongs_to :category
end

推荐答案

有一个验证将判断您的关联长度.试试这个:

class Product < ActiveRecord::Base
  has_many :product_categories
  has_many :categories, :through => :product_categories

  validates :categories, :length => { :minimum => 1 }
end

Ruby-on-rails相关问答推荐

参数数量错误(给定1个,预期为0个;必需关键字:IO、文件名)-活动存储

Rails + Turbo_stream自定义操作:我可以在没有Stimulus的情况下根据DOM状态做出有条件的响应吗?

Ruby on Rails 身份验证:设计注册不起作用

我需要在我的 Rails 7 应用程序中保留 app/assets/config/manifest.js 吗?

刺激不添加侦听器以搜索表单输入

计算总价(商品数量*商品价格)

你如何发布到 Capybara 中的 URL?

blueprint/screen.css 未预编译

理解 Gemfile.lock:删除 Gemfile.lock 然后再次运行 bundle install 可以吗?

如何判断是否已经在 ruby​​ on rails 的数据库事务中?

Rails ActiveRecord:验证单个属性

Ruby如何写入Tempfile

Rails:在 lib 目录中记录代码?

使用 RSpec 2 关闭一个规范的事务性固定装置

.increment vs += 1

在 where 查询中查找 nil has_one 关联

参数错误:范围主体需要可调用

我如何在具有活动记录的 Rails 中使用两个不同的数据库?

何时(如果)合并 ActiveRecord 迁移?

Rails 在 id 字段上重置种子的方法