現在Railsを勉強中のものです。
Rate(評価)モデルから、userが投稿した特定のhostへの評価一覧を検索して取得したいと思っています。
ruby
1class Rate < ApplicationRecord 2 belongs_to :agreement 3 has_one :user, through: :agreement 4 has_one :host, through: :agreement 5 6class Agreement < ApplicationRecord 7 belongs_to :user 8 belongs_to :host 9 has_one :rates 10end 11 12class Host < ApplicationRecord 13 has_many :agreements, dependent: :destroy 14 has_many :rates, through: :agreements 15end 16 17class User < ApplicationRecord 18 has_many :agreements, dependent: :destroy 19 has_many :rates, through: :agreements 20end
恥ずかしながら私が調べながら書いてみたのは以下のような感じです
ruby
1 def show 2 host = Host.find_by(myid: params[:id]) 3 rates = Rate.left_joins(:agreement).includes(agreement: :user).where(:agreement => {host_id: host.id}) 4 5 render rates.as_json( 6 only: %i[id star comment created_at], 7 include: { 8 agreement: { 9 only: [], 10 include: { 11 user: { 12 only: %i[name age] 13 } 14 } 15 } 16 } 17 ) 18 end 19
left_joinsで関連モデルを含めた検索を可能にして、
includesで必要な情報(関連しているagreement.userのname, age等)を取得するためのN + 1対策
whereで関連しているagreementのhost_idがパラメータから事前に検索しておいたhostのidに一致しているものを検索
というイメージでかきました。
しかしこれでは
ruby
1Mysql2::Error: Unknown column 'agreement.host_id' in 'where clause'
うまく関連モデルを紐づけられていないのでしょうか。
先輩エンジニアの皆様ご教授よろしくお願い致します。
回答2件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2022/04/06 12:19
2022/04/06 22:15