开发者

rails3 has_and_belongs_to_many customization

开发者 https://www.devze.com 2023-03-11 00:18 出处:网络
Book has_and_belongs_to_many Students Student has_and_belongs_to_many Books In BooksStudents model I want to add \"status\" field to store if it is rented,开发者_JAVA百科 bought ..etc. and be able to

Book has_and_belongs_to_many Students

Student has_and_belongs_to_many Books

In BooksStudents model I want to add "status" field to store if it is rented,开发者_JAVA百科 bought ..etc. and be able to select for example @student.books.rented or @student.books.where(:books_students=>{:status=>2})

Can I do that with HABTM?


AFAIK no, you will need a has_many :through setup..

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

so you can do something like @student.books or @student.student_books.where(:status =>2)

0

精彩评论

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