添加以下關聯到你的機型:
class Book < ActiveRecord::Base
has_many :bookmarks
has_many :users, :through => :bookmarks
end
# assuming bookmarks table has book_id and user_id columns.
class Bookmark < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
class User < ActiveRecord::Base
has_many :bookmarks
has_many :books, :through => :bookmarks
end
現在您可以以下呼叫:
u.books # books for a user
u.bookmarks # bookmarks for a user
# find the user and eager load books and bookmarks
User.find(params[:id], :include => [:books, :bookmarks])
b.users # users for a book
b.bookmarks # bookmarks for a book
# find the book and eager load users and bookmarks
Book.find(params[:id], :include => [:users, :bookmarks])
什麼是 「N/M的關係」? – 2010-05-03 16:21:17
n至m關係 – Markus 2010-05-03 16:24:44