开发者

Rails 3 associations

开发者 https://www.devze.com 2023-02-04 07:44 出处:网络
class User < ActiveRecord::Base has_many :books has_many :book_users has_many :books, :through => :book_users
class User < ActiveRecord::Base
  has_many :books
  has_many :book_users
  has_many :books, :through => :book_users
end

class Book < ActiveRecord::Base
  belongs_to :user
  has_many :book_users
  h开发者_如何转开发as_many :users, :through => :book_users
end

An user can write many books An book can belong to only one user An user can be a reader of different books An book can be read by different users

User.books 

should give me the books the user has written

User.books_read

should give me the books, are read by this user

How accomplish this ?

Second question, what is the simplest method to delete book_read from the user ? I mean

User.method_name(book_id) # what's the method name ?


First question:

You either use :source or :class_name.

has_many :books_read, :class_name => "Book", :through => :book_users

I don't know for sure if :class_name works with has_many :through. If it doesn't work, try this:

has_many :books_read, :source => :book, :through => :book_users

That should do the trick.

Second question:

As far as I know there isn't really a simple method to delete books from the books_read relation. You could create your own method to accomplish this. Just make sure you delete records from :book_users and not the has_many :through relation. Or else the books themselves will be deleted.

def delete_book(book_id)
  self.book_users.find_by_book_id(book_id).destroy
end

When using Rails 3 you can't use the find_by_... helper and need to use where.

def delete_book(book_id)
  self.book_users.where(:book_id => book_id).destroy
end

Now you can call this function as follows:

User.find(1).delete_book(2)

I hope that helps you out.

0

精彩评论

暂无评论...
验证码 换一张
取 消