i’m using rails 4.2.4. how can automatically load parent object when load child object? have
class myobject < activerecord::base belongs_to :address, class_name: 'address', foreign_key: :address_id, :autosave => true, dependent: :destroy but when call
@my_object = myobject.find(params[:id]) puts "address; #{@my_object.address} address_id: #{@my_object.address_id}" the output is
address; address_id: 6792 meaning no parent object loaded, though there address record tied it. automatically loaded when model is. how can that?
edit: in response wishalizer's suggestion, changed models to
class myobject < activerecord::base … belongs_to :address, inverse_of: :my_object and
class address < activerecord::base has_one :my_object, inverse_of: :address but still got error
nomethoderror (undefined method `includes' #<myobject:0x007fb7232415f8>): app/controllers/application_controller.rb:9:in `current_my_object' app/controllers/my_objects_controller.rb:5:in `edit' when applying suggestion given.
to include parent relationship in activerecord relation use .includes when create collection in controller. .includes symmetrically true, either parent child or child parent.
if explicitly invoke .includes, , should able reference parent child collection wish.
@my_object = myobject.find(params[:id]).includes(:address) model relationships required [new section]
append/insert inverse_of model relationship defs such
class myobject belongs_to :address, {...your model rels..}, inverse_of: :my_object ... end you must create symmetrical inverse_of in related model
class address has_many :my_objects, {...your model rels..}, inverse_of: :address ... end
Comments
Post a Comment