Rails具有许多关联性-使用包括

时间:2018-12-04 10:37:37

标签: ruby-on-rails ruby

共有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实现相同的功能?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

使用includesjoins,您可以使用哈希来嵌套查找器方法,例如find_bywhere

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)

使用references with includes

  includes(:rating).references(:rating).where("ratings.book_id = ? and ratings.user_id = ?", id, user_id).first

值得一读: https://blog.arkency.com/2013/12/rails4-preloading/