Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在Rails中通过联接表进行查询的最有效方法是什么?_Mysql_Ruby On Rails_Ruby On Rails 4.1 - Fatal编程技术网

Mysql 在Rails中通过联接表进行查询的最有效方法是什么?

Mysql 在Rails中通过联接表进行查询的最有效方法是什么?,mysql,ruby-on-rails,ruby-on-rails-4.1,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:

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

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

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

我发现了代码中的错误。源:用户类中的声明应为:

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

而不是:reader

假设当前的_配置文件实际上是一个用户对象?那么为什么不直接执行@my_books=current_profile.books是的,current_profile是会话中的一个用户对象。current_profile.books是用户编写的书籍列表,而不是确切拥有的书籍。Owned是通过一个联接表“ownerships”定义的。是的,它将朝另一个方向工作:Book.first。读者应该将用户送回来,但我认为您必须先定义ownerships关系,然后才能有很多:readers@japed你是说根据用户类中定义的关系,当前的_profile.owned_图书?是的,我是这么说的,很抱歉,我错过了你的书是协会的
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
  ...
@my_books = Book.joins(:readers).where("users.id = ?", current_profile.id)
has_many :owned_books, class_name: 'Book', through: :ownerships, source: :book