jmcharnes
jmcharnes

Reputation: 727

has_many and has_many through with a where clause

I have a users table where the users can be 'friends' with each other. The following relationship is in user.rb and works correctly:

has_many :friendships
has_many :friends, through: :friendships

When I run User.first.friendships or User.first.friends, everything works fine.

Here is my problem... I added a column on the friendships table called accepted_on. I only want friendships where accepted_on isn't nil. I used the following code to do that:

has_many :friendships, -> (object) { where.not(accepted_on: nil) }
has_many :friends, through: :friendships

Now if I run User.first.friendships, everything works according to plan. If I run User.first.friends I get the following error: ArgumentError: wrong number of arguments (0 for 1)

Is this possible?

Upvotes: 0

Views: 3930

Answers (1)

Sander Garretsen
Sander Garretsen

Reputation: 1723

You are not using object in your association. So why not remove it?

change

has_many :friendships, -> (object) { where.not(accepted_on: nil) }

to

has_many :friendships,-> { where.not(accepted_on: nil) }

Upvotes: 2

Related Questions