Relationships with wishes in Rails?

We create an application in which users have some kind of wish list

The user can have only one wish list and can add existing elements to this wish list however the Elements belong to other Users on the site

I need to have access to wishlist items through current_user.wishlist.items (im using Devise, so current_user is available)

i, although I add the wishlist_id column to the item table, but this does not work, because the items can belong to several wish lists.

it seems simple, but it’s hard for them to find a visualization of the relationship or a migration that should generate

+5
source share
1 answer
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

.

: " " :

, , ( Item Product ), HABTM "" "items", :

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

:

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

"", Ruby , , .

+5

All Articles