ruby-on-rails - 在 Rails 模型中 self 指代父亲字段中的男性和母亲字段中的女性?

标签 ruby-on-rails database postgresql models

我正在 Rails 中开发特定动物的数据库,我想要有“父亲”和“母亲”字段。

这可能不是什么大问题,但我希望用户能够在“父亲”字段中选择“仅男性”,在“母亲”字段中选择“仅女性”,然后验证它(只是为了确定)。然而现在,用户在从动物表中选择时会同时获得雄性和雌性。

这可能很容易解决,但是数据库怎么样?如何在数据库中定义这种特殊的关系? Rails 方面的首选方式是什么?我应该实现一个类似于 AnimalName.females 的方法吗?

其他信息:

数据库后端:PostgreSQL

最佳答案

在 Rails 方面,您可以使用自定义验证器来确保 Animalfather是男性(母亲是女性)。我不太了解你的具体型号,但这里有一个例子:

class Animal < ActiveRecord::Base

  belongs_to :father, :class_name => "Animal"
  belongs_to :mother, :class_name => "Animal"

  validate :ensure_mother_and_father_are_correct_gender

  private

  def ensure_mother_and_father_are_correct_gender
    if father.gender != "male"
      errors.add(:base, "Father is not a male")
    end

    if mother.gender != "female"
      errors.add(:base, "Mother is not a female")
    end
  end

end

这会阻止你的Animal如果提供了错误的 parent 性别,记录将被保存。您可能还必须在界面端引入某种验证 - 或者至少是选项限制,例如,如果您从下拉列表中选择他们的 parent ,则限制仅提供给男性和女性的选项:

<%= collection_select :father, Animal.where(:species => "monkey", :gender => "male"), ... %>或其他什么。

关于ruby-on-rails - 在 Rails 模型中 self 指代父亲字段中的男性和母亲字段中的女性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24204478/

相关文章:

php - mysql PHP 查询中的列名无效

sql - 使用具有数值的正则表达式

java - JPA - INSERT 后的 PK 属性问题

postgresql - postgreSQL 中的“where”子句错误

ruby-on-rails - SendGrid 修改电子邮件中的链接,它们不会重定向到正确的页面

javascript - 在 rails 上初始化应用程序 css 和 javascript 标签时,不显示完整日历标题工具栏按钮

python - python中的数据访问对象

ruby-on-rails - Rails 5.2 使用 Axios 请求返回 406

mysql - 无法使用 mysql 版本 0.3.20 创建 Rails 新应用程序

mysql - 如何确定 MySQL 中现有表的列分隔符