ActiveRecord’un Reflection modülünü kullanarak modellerin ilişkilerini nasıl öğrenebileceğimizi (beyle) ve birkaç method ile nasıl at koşturabileceğimizi anlatacağım.
reflections methodu sayesinde bir modelin hash olarak tüm ilişkilerini görebiliriz.
2.2.1 :051 > Post.reflections
{
"user" => #<ActiveRecord::Reflection::BelongsToReflection:0x007fb474a5ed50 @name=:user, @scope=nil, @options={}, @active_record=Post(id: integer, title: string, body: string, author_id: integer, is_published: boolean, created_at: datetime, updated_at: datetime), @klass=nil, @plural_name="users", @automatic_inverse_of=nil, @type=nil, @foreign_type="user_type", @constructable=true, @association_scope_cache={}, @scope_lock=#<Mutex:0x007fb474a5eaa8>>,
"comments" => #<ActiveRecord::Reflection::HasManyReflection .....,
"tags" => #<ActiveRecord::Reflection::ThroughReflection ......
}
:has_many, :has_one, :belongs_to argumanlarından birini alan reflect_on_all_associations methodu sayesinde ilişki tipine göre sonuçları görebiliriz. Bu methodun çıktısı bir array.
2.2.1 :007 > Post.reflect_on_all_associations(:belongs_to)
[
[0] #<ActiveRecord::Reflection::BelongsToReflection:0x007fb478871610 @name=:user, @scope=nil, @options={}, @active_record=Post(id: integer, title: string, body: string, author_id: integer, is_published: boolean, created_at: datetime, updated_at: datetime), @klass=nil, @plural_name="users", @automatic_inverse_of=nil, @type=nil, @foreign_type="user_type", @constructable=true, @association_scope_cache={}, @scope_lock=#<Mutex:0x007fb4788713e0>>
]
klass methodu ile direkt bağlı olduğu modele erişebilirken, class_name ile ismini öğrenebiliriz ve options ile daha neler neler var.
2.2.1 :032 > Post.reflect_on_all_associations(:belongs_to).first.klass
class User < ActiveRecord::Base {
:id => :integer,
:first_name => :string,
:last_name => :string,
:active => :boolean,
:created_at => :datetime,
:updated_at => :datetime
}
2.2.1 :033 > Post.reflect_on_all_associations(:belongs_to).first.class_name
"User"
2.2.1 :050 > User.reflections["comments"].options
{
:dependent => :destroy
}
Hala anlamadıysan senin için yapacağım bir şey yok. İstersen yazılı sor cevaplayayım, istersen ulak gönder soru işaretlerini gidereyim.
— Devlet Bahçeli (@dbdevletbahceli) 28 Ağustos 2015