gpt4 book ai didi

ruby-on-rails - 如何在多态关联中获取特定类型的所有子项

转载 作者:行者123 更新时间:2023-12-04 05:49:11 25 4
gpt4 key购买 nike

我写了一个有效的方法,但感觉不优雅。我想知道我是否错过了更好的方法。

我有一个像这样设置的多态关联;

class Employee < ActiveRecord::Base
has_many :phones, as: :phoneable
end

class Client < ActiveRecord::Base
has_many :phones, as: :phoneable
end

class Phone < ActiveRecord::Base
belongs_to :phoneable, polymorphic: true
end

我的手机 table 有标准 phoneable_id:integerphoneable_type:string列。

我想要做的是为先前选定的一组员工获取所有电话,例如
employees = Employee.where role: 'peon'

如果这是正常的 has_many关系然后我将我的电话查询写为;
Phone.where employee_id: employees

为了在多态关系中做到这一点,我将查询写为;
Phone.where phoneable_type: 'employee', phoneable_id: employees

这有效,但我觉得应该有比明确声明 phoneable_type 更好的方法来做到这一点。 .当出现一组员工时,Rails 是否有办法自动执行此操作,或者我是否过于简单?

最佳答案

你没有完全理解多态关联的重要性。如果您在模型中定义了它,则可以轻松获取如下记录:

假设您的员工表中有一个“Peon”角色:

@employee = Employee.where(role: 'peon').first

现在你可以像这样获取记录:
 @employee.phones

如果您想为具有“peon”角色的员工获取所有电话,您可以这样做:
@employees = Employee.where(role: 'peon')   

@peon_phones = @employees.map{|x| x.phones}

客户也一样:
@client = Client.first

@client.phones

它和你想象的一样简单。希望它会有所帮助。谢谢

关于ruby-on-rails - 如何在多态关联中获取特定类型的所有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18671019/

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