gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:46:07 25 4
gpt4 key购买 nike

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

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 的所有书籍的有效方法吗?然后我想列出拥有给定书籍的所有用户,因此希望能够以最有效的方式查询这两种方式。

最佳答案

我发现了我的代码中的错误。来源:User类中的声明应该是:

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

而不是:阅读器

关于mysql - 在 Rails 中查询连接表的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25935398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com