Module: Findable::Associations::ActiveRecordExt::ClassMethods
- Defined in:
- lib/findable/associations/active_record_ext.rb
Instance Method Summary collapse
Instance Method Details
#belongs_to(*args) ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/findable/associations/active_record_ext.rb', line 55 def belongs_to(*args) name, = Utils.parse_args(args) model = Utils.model_for(name, safe: true, **) if model && model < Findable::Base foreign_key = [:foreign_key].presence || name.to_s.foreign_key define_method(name) do model.find_by(model.primary_key => public_send(foreign_key)) end define_method("#{name}=") do |value| value = value ? value.public_send(model.primary_key) : nil public_send("#{foreign_key}=", value) end reflection = ActiveRecord::Reflection.create( :belongs_to, name.to_sym, nil, , self, ) ActiveRecord::Reflection.add_reflection(self, name.to_sym, reflection) else super end end |
#has_many(*args) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/findable/associations/active_record_ext.rb', line 7 def has_many(*args) name, = Utils.parse_args(args) model = Utils.model_for(name, collection: true, safe: true, **) if model && model < Findable::Base foreign_key = [:foreign_key].presence || model_name.name.foreign_key define_method(name) do model.where(foreign_key => public_send(self.class.primary_key)) end reflection = ActiveRecord::Reflection.create( :has_many, name.to_sym, nil, , self, ) ActiveRecord::Reflection.add_reflection(self, name.to_sym, reflection) else super end end |
#has_one(*args) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/findable/associations/active_record_ext.rb', line 31 def has_one(*args) name, = Utils.parse_args(args) model = Utils.model_for(name, safe: true, **) if model && model < Findable::Base foreign_key = [:foreign_key].presence || model_name.name.foreign_key define_method(name) do model.find_by(foreign_key => public_send(self.class.primary_key)) end reflection = ActiveRecord::Reflection.create( :has_one, name.to_sym, nil, , self, ) ActiveRecord::Reflection.add_reflection(self, name.to_sym, reflection) else super end end |