Check if association exists without incurring a database hit

天涯浪子 提交于 2019-12-25 11:45:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!