モデル 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