Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to extend belong_to functionality in rails
    primarykey
    data
    text
    <p>I'm building a gem and I want part of its functionality to extend <code>ActiveRecord::Associations::Builder::BelongsTo</code> but I cannot figure out how to do it </p> <p>so basically user should be able to specify:</p> <pre><code>class Event &lt; ActiveRecord::Base belongs_to :users, foo: true end </code></pre> <p>anyone know how to do it ?? </p> <p>This wont work:</p> <pre><code>module Mygem module BelongsToFoo def valid_options super + [:foo] end #... other functionality end end class ActiveRecord::Associations::Builder::BelongsTo extend MyGem::BelongsToFoo end </code></pre> <p>console</p> <pre><code>ActiveRecord::Associations::Builder::BelongsTo.valid_options.include? :foo #=&gt; false ... :( Event ArgumentError: Unknown key: foo </code></pre> <p><a href="https://github.com/rails/rails/blob/b5c4274a34d6815415111369d09e6249ccf588f1/activerecord/lib/active_record/associations/builder/belongs_to.rb" rel="nofollow noreferrer">belongs_to source code </a></p> <p>============================================================================= <strong>Update</strong></p> <p>flowing <a href="https://stackoverflow.com/a/18362678/473040">delwyns answer</a> I tried to have a another look on my code and he is right it should be included however <code>ActiveRecord::Associations::Builder::BelongsTo</code> has a variable <code>valid_options</code> as well.</p> <p>so I can do </p> <pre><code>ActiveRecord::Associations::Builder::BelongsTo.new(:a, :b, :c).valid_options.include? :foo # =&gt; true </code></pre> <p>but also</p> <pre><code>ActiveRecord::Associations::Builder::BelongsTo.valid_options.include? :foo # =&gt; true </code></pre> <p>so it should really look like this</p> <pre><code>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 </code></pre> <p>Even if I try this </p> <pre><code>module MyGem module BelongsToFoo def define_callbacks(model, reflection) raise "dobugging" end end end </code></pre> <p>nothing will happen, Rails completely ignore my method override </p> <p>So yes I can define my own option, however they do nothing :( any suggestions ? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload