user1032752
user1032752

Reputation: 871

Rails: has many relationship - determine which related object from within method

I have two classes with the following relationships/methods:

class Bar
  has_many :foos

  def bar_method
    #puts the specific foo that called it
  end
end

class Foo
  belongs_to :bar

  def foo_method
    bar.bar_method
  end
end

When calling foo_method on an instance of Foo, how I can tell which Foo called this from within bar_method? Is this possible?

Thanks

Upvotes: 0

Views: 128

Answers (1)

Ismael
Ismael

Reputation: 16730

Yes it is! Here is a simple way ;)

class Bar
  has_many :foos

  def bar_method foo
    puts foo
  end
end

class Foo
  belongs_to :bar

  def foo_method
    bar.bar_method self
  end
end

Upvotes: 1

Related Questions