Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Many to many relationship

I have a Bookmark model. I would like to have a List model. So my users can create Bookmark lists.

I've created a List scaffold with this command

rails generate scaffold List title:string
  1. A List can have many bookmarks
  2. A Bookmark can have many lists

Can someone help me to create List Bookmark relationship.?

It would be awesome if you can give me some resources to learn.

Update:

  1. A Bookmark can have many lists

Lets say I bookmarked http://stackoverflow.com. And say I have two lists like:

  1. Programming Help
  2. Favorite sites

Then I should be able to add my bookmark to both lists.

So I guess A Bookmark can have many lists is a valid statement.

like image 467
PrivateUser Avatar asked Mar 10 '14 18:03

PrivateUser


1 Answers

Applicable for => Rails 4:

app/model/Bookmark.rb

class Bookmark < ActiveRecord::Base
  has_and_belongs_to_many :lists
end

app/model/List.rb

class List < ActiveRecord::Base
  has_and_belongs_to_many :bookmarks
end

create a new migration

rails generate migration CreateJoinTableListBookmark List Bookmark

Migrate

rake db:migrate
like image 59
PrivateUser Avatar answered Oct 01 '22 11:10

PrivateUser