ruby-on-rails - Rails3 has_and_belongs_to_many 定制

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

预订has_and_belongs_to_many学生
学生has_and_belongs_to_many书籍

在 BooksStudents 模型中,我想添加“状态”字段来存储它是否被租用、购买等。并能够选择例如 @student.books.rented@student.books.where(:books_students=>{:status=>2})

我可以使用 HABTM 做到这一点吗?

最佳答案

据我所知不,您将需要一个 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)

关于ruby-on-rails - Rails3 has_and_belongs_to_many 定制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6276156/

相关文章:

ruby-on-rails - 如何过滤 Rails 中的对象,以便只有创建它的用户或管理员才能销毁该对象?

javascript - 用原型(prototype)改变现有的 JavaScript 对象函数?

ruby-on-rails-3 - 导轨/Rack : "ArgumentError: invalid %-encoding" for POST data

ruby - 根据 created_at 对 Spree 中的产品列表进行排序

mysql - 更新后的 ID 列仍然失败,并出现 RangeError

sql - 根据聚合的关联模型字段对条目进行分组

ruby-on-rails - rails s 在设计配置发送邮件时出错

ruby-on-rails - "The Ruby way"(mixins 和类重新打开)与依赖注入(inject)

javascript - 使用 javascript 提交两份表单,一份提交,一份不提交。不明白为什么?

ruby-on-rails - 将调用者应用程序堆栈跟踪与每个 sql 查询一起记录