Question

I have a User class used by Devise that has the following relationship

class User
  has_many :listings, dependent: :delete
  has_many :favorites, :class_name => 'Listing', as: :favorites, dependent: :delete

And a listing class

class Listing
  belongs_to :user
  belongs_to :favorites, :class_name => 'User', :inverse_of => :favorites

I can push current_user.listings << listing but I am unable to push current_user.favorites << listing

The push seems to be fine, no errors are thrown, but when I ask for current_user.favorites I get 0 results.

I'm wondering if I've set this relationship properly?

Was it helpful?

Solution

UPDATE:

You need to add a new model called Favorite and contains 2 fields: listing_id and user_id because the relation between users and favorites is many to many.

Or, you need to change the type of favorites in Listing model to Array like this way:

field :favorites, type: Array

Also, remove has_many :favorites ... in User model and add a getter method:

def favorites
  Listing.where(favorites: self.id)
end

and a setter method:

def favorites=(listing)
  Listing.find(listing.id).add_to_set(favorites: self.id)
end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top