lin*_*ndy 3 ruby activerecord ruby-on-rails
我基于 ahas_one或has_many关系动态构建查询。所以,我最终可以得到一个对象或 CollectionProxy。如何根据此结果测试查询是否使用has_one了has_many关系或关系?
我想检查类型,但是 CollectionProxy 的类型子类化了相关模型的类型。
此动态查询涉及调用对象上的属性,该属性可以是一个has_one或一个has_many关系。就像是:
class User < ActiveRecord::Base
has_one :profile
has_many :names
user = User.new
attr = 'profile' # or 'names'
user.send(attr) # I want to check whether this is a result of which of the two relations
Run Code Online (Sandbox Code Playgroud)
您可以使用 Active Record 的反射:
User.reflect_on_association(:profile)
#=> #<ActiveRecord::Reflection::HasOneReflection:0x007fd2b76705c0 ...>
User.reflect_on_association(:names)
#=> #<ActiveRecord::Reflection::HasManyReflection:0x007fd2b767de78 ...>
Run Code Online (Sandbox Code Playgroud)
在case声明中:
klass = User
attr = :profile
case klass.reflect_on_association(attr)
when ActiveRecord::Reflection::HasOneReflection
# ...
when ActiveRecord::Reflection::HasManyReflection
# ...
end
### OR by macro
case klass.reflect_on_association(attr).macro
when :belongs_to
# ...
when :has_many
# ...
when :has_one
# ...
end
Run Code Online (Sandbox Code Playgroud)
这基于模型 ( user.rb) 中的关联声明,即不访问数据库。