我正在 Rails 中开发特定动物的数据库,我想要有“父亲”和“母亲”字段。
这可能不是什么大问题,但我希望用户能够在“父亲”字段中选择“仅男性”,在“母亲”字段中选择“仅女性”,然后验证它(只是为了确定)。然而现在,用户在从动物表中选择时会同时获得雄性和雌性。
这可能很容易解决,但是数据库怎么样?如何在数据库中定义这种特殊的关系? Rails 方面的首选方式是什么?我应该实现一个类似于 AnimalName.females 的方法吗?
其他信息:
数据库后端:PostgreSQL
最佳答案
在 Rails 方面,您可以使用自定义验证器来确保 Animal
的father
是男性(母亲是女性)。我不太了解你的具体型号,但这里有一个例子:
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/