rails3 has_and_belongs_to_many自定义

时间:2011-06-08 08:32:07

标签: ruby-on-rails ruby-on-rails-3 activerecord has-and-belongs-to-many

预订has_and_belongs_to_many学生 学生has_and_belongs_to_many图书

在BooksStudents模型中,我想添加“status”字段来存储,如果它是租来的,买了..etc。并且能够选择例如@student.books.rented@student.books.where(:books_students=>{:status=>2})

我可以用HABTM做到吗?

1 个答案:

答案 0 :(得分:3)

AFAIK不,你需要一个has_many:通过设置..

class Book < ActiveRecord::Base
  has_many :books_students  
  has_many :students, :through => :books_students
end

class BooksStudent  < ActiveRecord::Base
  belongs_to :book  
  belongs_to :student 
end 

classStudent  < ActiveRecord::Base 
  has_many :books_students  
  has_many :books, :through => :books_students  
end

因此您可以执行@student.books@student.student_books.where(:status =>2)

之类的操作