現在Rails apiを使用してアプリ開発を勉強中です。
N+1問題対策でinludes検索をしたいと考えております。
先ずモデルの定義を提示させてください。
ruby
1class UserNotice < ApplicationRecord 2 belongs_to :user 3 belongs_to :source, polymorphic: true, optional: true 4end 5 6class Agreement < ApplicationRecord 7 belongs_to :user 8 belongs_to :host 9 belongs_to :room 10 has_many :user_notices, as: :source 11end 12 13class Room < ApplicationRecord 14 belongs_to :user 15 belongs_to :host 16 has_many :user_notices, as: :source 17end 18 19 20class Host < ApplicationRecord 21 has_many :agreements 22 has_many :rooms 23end
user | user_notices | agreements | rooms | host |
---|---|---|---|---|
id | id | id | id | id |
user_id | user_id | user_id | ||
source(type,id) | host_id | host_id | ||
room_id |
参考にさせていただいたサイト
https://himakan.net/program/ror/polymorphic_includes
の通りに
ruby
1# user_notices_controller.rb 2class UserNotice < ApplicationRecord 3 belongs_to :source, polymorphic: true, optional: true 4 belongs_to :user 5 6 belongs_to :agreement, ->{ joins(:user_notices).where(user_notices: {id: UserNotice.where(source_type: 'Agreement')})}, foreign_key: :source_id
ruby
1def index 2 notice = UserNotice.where(user: current_api_user).includes(agreement: :host) 3 render json: notice , status: :ok 4end
としました。
期待通りに、user_noetice.agreement.hostが取得オブジェクトが返ってくると思っていたのですが、
# エラー ActiveRecord::ConfigurationError in Api::UserNoticesController#index Can't join 'Agreement' to association named 'user_notices'; perhaps you misspelled it?
上記エラーが出現しました。
他のサイトを探しても解決できませんでした。設定に不備がありますでしょうか?
追記したほうが良い情報がありましたらすぐに追記します。
先輩エンジニアの皆様よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。