ruby-on-rails - 验证 has_and_belongs_to_many 的存在

标签 ruby-on-rails has-and-belongs-to-many

嗨,我在模型中使用 has_and_belongs_to_many。
我想为种类设置存在的 valitor。
并将每个核心的最大种类数设置为 3

class Core < ActiveRecord::Base
  has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id'
end

我能怎么做?

谢谢

最佳答案

validate :require_at_least_one_kind
validate :limit_to_three_kinds

private

def require_at_least_one_kind
  if kinds.count == 0
    errors.add_to_base "Please select at least one kind"
  end
end

def limit_to_three_kinds
  if kinds.count > 3
    errors.add_to_base "No more than 3 kinds, please"
  end
end

关于ruby-on-rails - 验证 has_and_belongs_to_many 的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158188/

相关文章:

ruby-on-rails - 如何测试rails中是否存在参数

mysql - 可以实现 has_and_belongs_to_many 关联

ruby-on-rails - HABTM 与 rails API 的关系不起作用

ruby-on-rails - 在 rails 4 迁移中加入表注释

ruby-on-rails - 创建模型实例时如何建立 has_and_belongs_to_many 关联

ruby-on-rails - 将 Rails 5.2 升级到 6.0 时出现错误数量的参数错误

ruby-on-rails - 我如何找到可以贡献的开源项目(Ruby、Rails)

ruby-on-rails - RoR 的 "magic"命名空间解析是如何工作的?

ruby-on-rails - Rails 克隆记录

ruby-on-rails - 如何通过关联(具有中介模型的值)为多对多设置固定装置?