Reputation: 4524
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
Can someone help me to create List Bookmark relationship.?
It would be awesome if you can give me some resources to learn.
- A Bookmark can have many lists
Lets say I bookmarked http://stackoverflow.com
. And say I have two lists like:
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.
Upvotes: 5
Views: 10957
Reputation: 4524
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
Upvotes: 35
Reputation:
I think that there is many to many relationship.
for solving this problem. A new model ListBookmark Will be created.
ListBookmark basic attributes: list_id bookmark_id
according to requirement more attribute may be added.
class List < ActiveRecord::Base
attr_accessible :title
has_many :list_bookmarks
has_many :bookmarks, through: :list_bookmarks
end
class ListBookmark < ActiveRecord::Base
attr_accessible :bookmark_id, :list_id
belongs_to :list
belongs_to :bookmark
end
class Bookmark < ActiveRecord::Base
attr_accessible :title
has_many :list_bookmarks
has_many :lists, through: :list_bookmarks
end
Upvotes: 2
Reputation: 2952
There are two model Bookmark and List.
It is case of Many to Many relationship.
To resolve this problem, there will be introduce one more Model(ListBookMark) to solve many to many relationship.
ListBookmark attributes:
list_id bookmark_id
there may be more attribute according to requirements.
class List < ActiveRecord::Base
attr_accessible :title
has_many :list_bookmarks
has_many :bookmarks, through: :list_bookmarks
end
class ListBookmark < ActiveRecord::Base
attr_accessible :bookmark_id, :list_id
belongs_to :list
belongs_to :bookmark
end
class Bookmark < ActiveRecord::Base
attr_accessible :title
has_many :list_bookmarks
has_many :lists, through: :list_bookmarks
end
I think that It will helpful to solve this problem.
To read about relationship click here
Upvotes: 1
Reputation: 451
Haven't tested it, but this is how it works
class Bookmark < ActiveRecord::Base
has_and_belongs_to_many :bookmark_lists
end
class BookmarkList < ActiveRecord::Base
has_and_belongs_to_many :bookmarks
end
And you will need to have migrations for each and a migration for a bridge-table (I'm assuming you want a title for a bookmark and for the lists):
rails generate model Bookmark title
rails generate model BookmarkList title
rails generate model BookmarkListsBookmarks bookmark_list_id:integer bookmark_id:integer
Not sure if rails wants BookmarkListsBookmarks or BookmarksBookmarkLists if it throws an error just try the other one.
Upvotes: 2