问题
Is there a way to check if an ActiveRecord's belongs_to
association exists without incurring a database query.
I'm using example_association.present?
to check and it results in the association being loaded if it does.
All I want to know is if the association exists.
回答1:
You could use reflect_on_all_associations as:
Foo.reflect_on_all_associations(:belongs_to).map(&:name).include?(:example_assoc)
Where :example_assoc
is one of the belongs_to
association.
Or if you have an instance of model class:
@foo.class.reflect_on_all_associations(:belongs_to).map(&:name).include?(:example_assoc)
回答2:
class Article < ActiveRecord::Base
has_many :pages
end
class Page < ActiveRecord::Base
belongs_to :article
end
Check if the association exist by:
Article.reflect_on_association(:pages)
or
Page.reflect_on_association(:article)
If the association not exist, the return value of Page.reflect_on_association(:article)
will be nil
, otherwise it puts like :
#<ActiveRecord::Reflection::HasManyReflection:0x00007fbe099d9c10
@active_record=
Page(id: integer, name: string),
@association_scope_cache={},
@automatic_inverse_of=false,
@constructable=true,
@foreign_type="article_type",
@klass=nil,
@name=:article,
@options={:autosave=>true},
@plural_name="articles",
@scope=nil,
@scope_lock=#<Thread::Mutex:0x00007fbe099d9990>,
@type=nil>
It mains the association exist,and you can get more info about it.
回答3:
If you're trying to minimise the number of queries perhaps you should consider using "include" to eager load the associations.
Eg.
foos = Foo.includes(:example_associations).all
And then later in a loop or something when invoking
foo.example_associations.present?
Should not invoke any additional database queries
来源:https://stackoverflow.com/questions/22646800/check-if-association-exists-without-incurring-a-database-hit