gpt4 book ai didi

ruby-on-rails - Rails 接受_nested_attributes_for。使用 reject_if 通过使用父对象的属性来拒绝对象

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:51 25 4
gpt4 key购买 nike

我有两个模型在 rails 上。首先是患者模型

class Patient

attr_accessible :name, :age, :sex, :female_attributes
has_one :female, dependent => :destroy
accepts_nested_attributes_for :female, allow_destroy => true

end

第二个模型包含女性患者的额外信息

class Female
belongs_to :patient
attr_accessible :patiend_id, :pregrnant_now: :childbirths
end

注意:我没有创建数据库架构,也无法更改它。

所以我的问题是:如何通过检查患者对象中的 :sex 属性来拒绝将女性对象保存在数据库中?

我试过了

reject_if => lambda { |a| a['sex'].to_i == 0 ) }

但是没有用。 ( sex 是一个整数,男性为 0,女性为 1)

有什么想法吗??

最佳答案

我知道这是旧的,但我刚遇到同样的问题。您可以使用 reject_if 并在您的患者模型中传递一个符号。

class Patient

attr_accessible :name, :age, :sex, :female_attributes
has_one :female, dependent => :destroy
accepts_nested_attributes_for :female,
reject_if: :female_patient?,
allow_destroy => true

def female_patient?
self.sex.to_i == 1
end
end

关于ruby-on-rails - Rails 接受_nested_attributes_for。使用 reject_if 通过使用父对象的属性来拒绝对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15664306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com