関連するテーブルが2つあり、親オブジェクトの+/-%5のtshirts(子テーブル)の長さ属性に基づいてフィルタを適用したいStudentのheight属性Rails:子と親の属性計算に基づくフィルタリング
残念ながら、親テーブルの名前に未定義のメソッドエラーが発生します。
DBテーブル:
Student
------
id
name
height
Tshirt
------
id
color
student_id
length
MODELS:
class Student < ApplicationRecord
has_many :tshirts
class Tshirt < ApplicationRecord
belongs_to :student
def self.suitablesize
joins(:student).where('length < ? AND length > ?', (1.05*self.student.height),(0.95*self.student.height))
end
コントローラー:
def index
@tshirts = Tshirt.all.suitablesize
end
エラーメッセージ:
undefined method `student' for #<Class:0xc88cdc0>
EDIT: 私は所有者の学生に適したすべてのTシャツを手に入れたいと思います。したがって、私は、1人の学生がスコープメソッドの入力パラメータになることを望んでいません。どのようにしてこの問題を解決できるか考えていますか?
'Tshirt.all.suitablesize'を使う必要はありません。 'Tshirt.suitablesize'はすでにActiveRecordスコープを返すので、' all'はNoOpです。 – ulferts