gpt4 book ai didi

ruby-on-rails - has_many 关系的实际类别是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:53 24 4
gpt4 key购买 nike

基础入门:

class User 
has_many :programs, :through => :memberships
has_many :memberships
end

class Program
end

class Membership
belongs_to :user
belongs_to :program
end

控制台:

User.new.save
Program.new.save
User.programs << Program.first

User.first.programs.class
# => Array
User.first.programs.methods.grep /where/
# => []
User.first.programs.where :id => 1
# => [#<Program id: 1>]
User.first.programs.where(:id => 1).class
# => ActiveRecord::Relation

所以问题是 User.first.programs,has_many 方法,似乎返回一个像 ActiveRecord::Relation 一样的结果,并接受像Relation,但 self 标识为 Array 并与类 Array 的实例共享其方法。

那么是什么给了?

最佳答案

这确实令人惊讶,不知道它是否是最好的解决方案,但至少它被记录在案(在 AssociationProxy 类中):

the association proxy in blog.posts has the object in blog as @owner, the collection of its posts as @target, and the @reflection object represents a :has_many macro.

This class has most of the basic instance methods removed, and delegates unknown methods to @target via method_missing. As a corner case, it even removes the class method and that’s why you get

blog.posts.class # => Array though the object behind blog.posts is not an Array, but an ActiveRecord::Associations::HasManyAssociation.

关于ruby-on-rails - has_many 关系的实际类别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010089/

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