2

I'm trying to figure out something in a Rails application. We have a class Site that has themes (of class Theme) and when a site uploads a theme it can install it for a specific site. So I'm tracking down the code for that and I see it calls the method 'build' like this:

@theme = @current_site.themes.build(params[:theme])

the themes method simply returns an array of Theme objects associated with that site. So in the rails console I tried this (result included):

>> site.themes.method(:build).__file__
NameError: undefined method `build' for class `Array'

and then I tried this:

>> site.themes.respond_to? :build
=> true

So my question is twofold, how can I find out where 'build' is defined so I can understand how it works?, and can someone explain to me how a method like 'build' works in terms of it being able to be called at the end of an Array object that has no such method? Thanks!

Craig
  • 419
  • 4
  • 19

1 Answers1

4

Given your Site model has_many :themes, this is one of the association methods that automatically gets added to it by the association.

If you want some more reading material, check out the Association Basics Guide (for example, the section on has_many associations), this lists all of the methods added along with the parameters they take.

As to the exactly how this works, the .themes object is actually an AssociationProxy (source here), with an Array as its target, not an Array itself. .class returns 'Array' because the proxy itself does not respond to the .class method, and instead forwards it to its target (the Array) via method_missing. This answer gives a more detailed explanation.

Community
  • 1
  • 1
zkcro
  • 4,344
  • 1
  • 24
  • 22