简体   繁体   中英

Rails associations. How do they work?

What is the exact purpose of associations? I understand what the relationships mean and when to use each type for example:

belongs_to, has_many, has_one , has_and_belongs_to_many, ect

but i dont quite understand what purpose they serve in terms of how the connect things within rails. Any input would be appreciated. Thanks!

What you're calling "associations" I would call "macros". That is, the belongs_to , has_many etc. macros are simply class methods being called on your ActiveRecord objects which, when called, define a bunch of functionality based on the association name.

So, what you're asking is: What functionality do these macro methods define? The answer for that lies within the Rails documentation for each of these methods:

And, even more, you should read the overall documentation on ActiveRecord::Associations::ClassMethods .

But, in short, these macros define methods with names based on the association names you pass into them. So, for example:

belongs_to :my_object

Will define, as a greatly-simplified example:

def my_object
  MyObject.find_by_id(my_object_id)
end

So it's basically like metaprogramming your objects to have the methods needed to find the other, associated objects, update their collections, and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM