Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wishlist relationships in Rails?

Im building an app where Users have some sort of wishlist

a User can have only one wishlist, and can add existing Items to that wishlist however the Items belong to other Users on the site

I need to be able to access the wishlist items through current_user.wishlist.items (im using Devise so current_user is available)

i though of adding a wishlist_id column to the items table, but that wouldnt work since items can belong to multiple wishlists.

this seems simple but im having a hard time visualizing the relationship or the migration im supposed to generate

like image 738
daniel Avatar asked Apr 29 '11 12:04

daniel


1 Answers

class User < ActiveRecord::Base

  has_one :wishlist # or belongs_to :wishlist, it depends which you prefer

end

class Wishlist < ActiveRecord::Base

  belongs_to :user
  has_and_belongs_to_many :items

end

And of course:

./script/rails generate migration create_item_wishlists wishlist_id:integer item_id:integer

to create join table between items and wishlists.

UPDATE: To answer "frank blizzard" question in comment:

Let's say you have the same structure as in my answer (just change Item to Product or other model name), with HABTM relationship you just need to add new "item" to collection of "items", and then save wishlist:

@user.wishlist.items << item
@user.wishlist.save

You can make it method in user:

class User
  def add_to_wishlist(item)
    wishlist.items << item
  end
end

If you want to remove or modify collection of "items", just use any Ruby method from Array and then save wishlist, which will check differences for you and save only changes.

like image 188
MBO Avatar answered Oct 18 '22 05:10

MBO