查询Rails中的连接表最有效的方法?

时间:2014-09-19 13:41:58

标签: mysql ruby-on-rails ruby-on-rails-4.1

我有以下模型和模型间关系:

class User < ActiveRecord::Base
  # 1. Serialized constants: 
  # 2. Constants:
  # 3. Associations/Inter-model Relationships

  has_many :ownerships, foreign_key: :reader_id, dependent: :destroy
  has_many :owned_books, class_name: 'Book', through: :ownerships, source: :reader
  ...
end

class Book < ActiveRecord::Base
  # 1. Serialized constants defined below:
  # 2. Constants defined below:
  # 3. Associations/Inter-model Relationships
    has_many :readers, class_name: 'User', through: :ownerships
    has_many :ownerships, dependent: :destroy
...
end

加入:所有权如下:

class Ownership < ActiveRecord::Base
  # 1. Serialized constants defined below:
  # 2. Constants defined below:
  # 3. Associations/Inter-model Relationships
    belongs_to :book
    belongs_to :reader, :class_name => 'User'
  # 4. Attribute accessors
  # 5. Gem configurations e.g.: acts_as_authentic
  # 6. Validations
    validates :reader_id, presence: true
    validates :book_id, presence: true
    validates_uniqueness_of :book_id, :scope => :reader_id
  ...

现在列出current_user拥有的所有书籍,我正在使用:

@my_books = Book.joins(:readers).where("users.id = ?", current_profile.id)

这是查找current_user的所有书籍的有效方法吗?然后我想列出拥有给定书籍的所有用户,以便能够以最有效的方式查询这两种方式。

1 个答案:

答案 0 :(得分:0)

我弄清楚了代码中的错误。来源:USer类中的声明应该是:

has_many :owned_books, class_name: 'Book', through: :ownerships, source: :book

而不是:读者