开发者

rails3 has_and_belongs_to_many customization

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜