JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Scoping a `has_one` relationship

オープン
#627 コメント 6 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
Ruby
スター
2.3k
フォーク
546
PR マージ指標
30日以内にマージされた PR はありません

説明

After searching for a while, the answer here isn't obvious to me, so I thought I'd bring it up as an issue for reference.

I have 3 models:

class User < ActiveRecord::Base
  has_many :answers
end

class Question < ActiveRecord::Base
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question
end

What I'd like to do is include the current_user_answer in a questions#show request, like so: /api/questions/123?include=current_user_answer. It seems like I should be able to write my QuestionResource as follows:

class QuestionResource < JSONAPI::Resource
  has_many :answers

  has_one :current_user_answer, class_name: 'Answer'

  # doesn't get called
  def self.record_for_current_user_answer(options={})
        current_user = options[:context][:current_user]
        AnswerResource.records(options).find_by(
          question: @model,
          user: current_user
        )
  end

  # doesn't get called either
  def current_user_answer(options={})
        current_user = options[:context][:current_user]
        AnswerResource.records(options).find_by(
          question: @model,
          user: current_user
        )
  end
end

Neither of these methods get called; instead, I get an exception "Association named 'current_user_answer' was not found on Question; perhaps you misspelled it?" Well, by definition here I'm trying to avoid writing a query method directly on the model, and anyways such a query method or association would need to get the context passed in from the enclosing Resource.

In short, there seems to be no documented way to scope an included associated to something in the context. Or am I missing something? What's the canonical way to get this related resource without an extra request?

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

ここで説明されている QuestionResource のリレーション宣言と /api/questions/123?include=current_user_answer リクエストから始め、association-not-found exception を再現し、include された has_one リレーションがどのように解決されるかを追跡してください。コンテキストスコープの検索がサポートされているかを確認し、追加のリクエストなしで関連する Answer を返すための標準的な方法を文書化または実装してください。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
rails, ruby
領域
api, backend
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。