1

モデル QuizCategoryWeight に並べ替え順序を課すために、デフォルトのスコープを使用しようとしています。目標は、@possible_answer.quiz_category_weights が重みをソートされた順序で返すようにすることです。

更新: 問題を絞り込んで、デフォルトのスコープは「注文」メソッドだけを持っている限り機能するように見えますが、「インクルード」メソッドが「注文」メソッドとチェーンされている場合はそうではありません。ただし、この連鎖は名前付きスコープに対して機能します。

それは私の開発環境でしょうか?それともRailsのバグでしょうか?

私はWindowsを使用しているので、おそらくそれが問題です。現在、ruby 2.0.0p645 (2015-04-13) [i386-mingw32] と Rails 4.2.4...

QuizCategoryWeight でデフォルトのスコープを使用する以下は、機能しないようです。

class QuizCategoryWeight < ActiveRecord::Base
    #trying to use a default scope, but does not work
    default_scope { includes(:quiz_category).order("quiz_categories.sort_order") }

    belongs_to :possible_answer, inverse_of: :quiz_category_weights,
        class_name: 'QuizPossibleAnswer', foreign_key: 'possible_answer_id'

    belongs_to :quiz_category

end

class QuizPossibleAnswer < PossibleAnswer
    has_many :quiz_category_weights, 
        #does not work whether the line below is used or not
        ->{ includes(:quiz_category).order("quiz_categories.sort_order") }, 
        inverse_of: :possible_answer, 
        dependent: :destroy, 
        foreign_key: 'possible_answer_id' 
end

class QuizCategory < ActiveRecord::Base
    default_scope { order :sort_order }
end  

名前付きスコープを使用すると、機能します。ただし、これは、コレクション「f.object.quiz_category_weights.sorted」を使用するために、フォーム ビルダーに引数を追加する必要があることを意味します。

class QuizCategoryWeight < ActiveRecord::Base
    # named scope works...
    scope :sorted,  ->{ includes(:quiz_category).order("quiz_categories.sort_order") }

    belongs_to :possible_answer, inverse_of: :quiz_category_weights,
        class_name: 'QuizPossibleAnswer', foreign_key: 'possible_answer_id'

    belongs_to :quiz_category

end

class QuizPossibleAnswer < PossibleAnswer
    has_many :quiz_category_weights, 
        inverse_of: :possible_answer, 
        dependent: :destroy, 
        foreign_key: 'possible_answer_id' 
end
4

2 に答える 2

0

このincludesメソッドは、Rails にデータベース クエリを減らすためのヒントを与えるためにリレーションに導入されました。それは言います:タイプAのオブジェクトをフェッチするときは、関連するオブジェクトもフェッチします。後で必要になるため、1つずつフェッチするべきではありません(N + 1クエリの問題

は、includes最初に 2 つのデータベース クエリで実装されました。最初にすべて A、次に A からの ID の 1 つを持つすべての B。現在includes、SQL 結合を使用してデータベースクエリを 1 つだけ持つことがよくあります。しかし、これは内部最適化です。概念はオブジェクト指向です。A からオブジェクトが必要な場合は、A を介して B を取得します。したがって、含まれている B から A に順序を戻すと、元のincludes.

于 2015-10-02T22:19:40.820 に答える
0

Railsフレームワーク全般または私のWindowsバージョンのいずれかで、デフォルトのスコープで「includes」を使用するとバグがあると思います。

ただし、「結合」を使用しても機能することがわかりました。私は QuizCategory の他の属性を使用していないので、私のユース ケースにも適しています。結合されたテーブルの 'sort_order' 属性を使用して並べ替えたいだけです。

固定コードは次のとおりです。

class QuizCategoryWeight < ActiveRecord::Base
    default_scope { joins(:quiz_category).order("quiz_categories.sort_order") }

    belongs_to :quiz_category
end
于 2015-10-02T15:34:52.807 に答える