共有3个表格-图书,用户,评分
Book表包含标题,id,描述
评分表包含-id,value,user_id,book_id
要满足的条件如下
用户可以添加许多评分
用户只能为一本书添加一个评分
关联如下
book.rb
has_one :rating
has_many :users, through: :rating
rating.rb
belongs_to :book
belongs_to :user
user.rb
has_one :rating
has_many :books, through: :rating
books_controller.rb
def show
@book = Book.fetch_record(params[:id], @current_user.id)
set_book if @book.blank?
json_response(@book)
end
book.rb
def self.fetch_record(id, user_id)
joins(:rating).where("ratings.book_id = ? and ratings.user_id = ?", id, user_id).first
end
当前,我正在使用联接来获取详细信息。
如何使用include实现相同的功能?
任何帮助将不胜感激。
答案 0 :(得分:2)
使用includes
或joins
,您可以使用哈希来嵌套查找器方法,例如find_by
或where
:
Book.includes(:rating).find_by(ratings: { book_id: id, user_id: user_id }
# or
Book.includes(:rating).where(ratings: { book_id: id, user_id: user_id }.first
# nested hash also works with `joins`, just for FYI
Book.joins(:rating).where(ratings: { book_id: id, user_id: user_id }.first
ratings:
应该是表名(ratings
),而不是关联名(rating
)。嵌套的Hash可以按您希望的更深:即:
# say your `User` model `has_many :comments` having `:content` attribute
Book.includes(rating: { user: :comments }).where(
ratings: { users: { comments: { content: 'HELLO WORLD' } } }
)
# or following also works (because there are no conflicts of association names in the query
Book.includes(rating: { user: :comments }).where(
comments: { content: 'HELLO WORLD' }
)
答案 1 :(得分:0)
includes(:rating).references(:rating).where("ratings.book_id = ? and ratings.user_id = ?", id, user_id).first