Joe Essey
Joe Essey

Reputation: 3527

Ruby undesired object is being added to array instead of correct object

Associations:

class Foo
  has_many :foo_subscribers
end

class FooSubscriber
  belongs_to :foo
  belongs_to :user
end

class User
  has_many :foo_subscribers
  belongs_to :employee
end

class Employee
  has_one :user
end

The following code is adding a User object to the array, despite the explicit call to User's Employee

#foo.rb

employees_to_notify = Array.new

foo_subscribers.each do |user|
  employees_to_notify << user.employee
end

All of the appropriate data is present for the test. Through debugging, I can evaluate user.employee as an employee object right on the line where it's added to the array.

How is this possible? I've tried various things like iterating over the array and converting any User objects to Employees. That also failed.

Upvotes: 0

Views: 38

Answers (2)

Joe Essey
Joe Essey

Reputation: 3527

I was trying to get foo_subscriber.employee rather than foo_subscriber.user.employee. I was attempting to perform an operation on the wrong type.

Upvotes: 0

Coburn Berry
Coburn Berry

Reputation: 282

It looks like you are iterating over foo_subscribers, but then naming them as users in the pipes? Are foo_subscribers users?

Upvotes: 1

Related Questions