我有2个关联的表,并希望应用基于父对象的+/-%5的tshirts(子表)长度属性的过滤器学生的高度属性Rails:基于父母的属性计算
不幸的是,我收到父表名的未定义方法错误。
DB表:
Student
------
id
name
height
Tshirt
------
id
color
student_id
length
模型:
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>
编辑: 我想得到适合所有者学生适用的所有t恤。因此,我不想找到一个学生作为范围方法的输入参数。你有什么想法我可以解决这个问题吗?
你不需要使用'Tshirt.all.suitablesize'。 'Tshirt.suitablesize'就够了,因为它已经返回一个ActiveRecord作用域,因此'all'是一个NoOp。 – ulferts