Wishlist relationships in Rails? -


im building app users have sort of wishlist

a user can have 1 wishlist, , can add existing items wishlist items belong other users on site

i need able access wishlist items through current_user.wishlist.items (im using devise current_user available)

i though of adding wishlist_id column items table, wouldnt work since items can belong multiple wishlists.

this seems simple im having hard time visualizing relationship or migration im supposed generate

class user < activerecord::base    has_one :wishlist # or belongs_to :wishlist, depends 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 , wishlists.

update: answer "frank blizzard" question in comment:

let's have same structure in answer (just change item product or other model name), habtm relationship need add new "item" collection of "items", , save wishlist:

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

you can make method in user:

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

if want remove or modify collection of "items", use ruby method array , save wishlist, check differences , save changes.


Comments