how to extend belong_to functionality in rails
activerecord, ruby-on-rails, ruby-on-rails-3
Solution
There is a built in approach for extending association proxies, see http://guides.rubyonrails.org/association_basics.html#association-extensions
class Event < ActiveRecord::Base
belongs_to :users, :extend => MyGem::SpecialTouch
end
module MyGem
module SpecialTouch
def touch
# do the magic
end
end
end
Then you could of course override or alias chain `belongs_to` so that it pops your `:foo` option from options hash, converts it to proper `:extend => ...` and (really or effectively) calls `belongs_to`.
Problem
I'm building a gem and I want part of its functionality to extend `ActiveRecord::Associations::Builder::BelongsTo` but I cannot figure out how to do it so basically user should be able to specify: ``` class Event < ActiveRecord::Base belongs_to :users, foo: true end ``` anyone know how to do it ?? This wont work: ``` module Mygem module BelongsToFoo def valid_options super + [:foo] end #... other functionality end end class ActiveRecord::Associations::Builder::BelongsTo extend MyGem::BelongsToFoo end ``` console ``` ActiveRecord::Associations::Builder::BelongsTo.valid_options.include? :foo #=> false ... :( Event ArgumentError: Unknown key: foo ``` belongs_to source code ============================================================================= Update flowing delwyns answer I tried to have a another look on my code and he is right it should be included however `ActiveRecord::Associations::Builder::BelongsTo` has a variable `valid_options` as well. so I can do ``` ActiveRecord::Associations::Builder::BelongsTo.new(:a, :b, :c).valid_options.include? :foo # => true ``` but also ``` ActiveRecord::Associations::Builder::BelongsTo.valid_options.include? :foo # => true ``` so it should really look like this ``` module MyGem module BelongsToFoo extend ActiveSupport::Concern included do self.valid_options += [:foo] end def valid_options super + [:foo] end def define_callbacks(model, reflection) # this wont get executed add_foo_callbacks(model, reflection)# if options[:foo] super end def add_foo_callbacks(model, reflection) # therefore this wont either end end end ``` Even if I try this ``` module MyGem module BelongsToFoo def define_callbacks(model, reflection) raise "dobugging" end end end ``` nothing will happen, Rails completely ignore my method override So yes I can define my own option, however they do nothing :( any suggestions ?