Trung Tran
Trung Tran

Reputation: 13721

Reference an object's parent ruby rails

I have an Opportunity model that has Links as a nested resource. I wrote a callback so that whenever I add a new link, the built-in "updated_at" attribute for my model opportunity is updated to equal Time.now. However, I'm not sure how to reference the Opportunity model. I want to do something like this:

This is what I would put in my Link model, which is a nested resource of my Opportunity model:

class Link < ActiveRecord::Base
belongs_to :opportunity

after_save :update_updated_at

def update_updated_at
  @opportunity.updated_at = Time.now #this line is where I am unsure of how to reference the link's Opportunity parent
end
end

Thanks!

Upvotes: 0

Views: 84

Answers (2)

Fred
Fred

Reputation: 8602

If a Link object @link belongs_to an Opportunity object @opp, you can find @opp if you know @link via the ActiveRecord relation opportunity. See http://guides.rubyonrails.org/association_basics.html for more details.

Given a link record, find the parent opportunity record: @opp = @link.opportunity

So you could write self.opportunity.updated_at = Time.now

Upvotes: 1

tadman
tadman

Reputation: 211570

Links in ActiveRecord are always accessed through method names. There is no instance variable called @opportunity, so that's equivalent to calling updated_at= on nil.

What you probably want is:

def update_parent
  return unless (self.opportunity)

  self.opportunity.updated_at = Time.now
  self.opportunity.save
end

From an implementation perspective this is a little rude as the Link object is bossing around the Opportunity one. That's usually something a controller should be doing.

Upvotes: 1

Related Questions