Ruby on rails Rails:基于子对象的过滤&;家长';s属性计算
我有两个相关联的表,并且希望基于tshirts(子表)长度属性应用过滤器,该属性是父对象学生高度属性的+/-%5 不幸的是,我收到了父表名称的未定义方法错误 数据库表:Ruby on rails Rails:基于子对象的过滤&;家长';s属性计算,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我有两个相关联的表,并且希望基于tshirts(子表)长度属性应用过滤器,该属性是父对象学生高度属性的+/-%5 不幸的是,我收到了父表名称的未定义方法错误 数据库表: Student ------ id name height Tshirt ------ id color student_id length 型号: class Student < ApplicationRecord has_many :tshirts class Tshirt < Applicatio
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
错误消息:
undefined method `student' for #<Class:0xc88cdc0>
未定义的方法“student”#
编辑:
我想购买所有适合业主学生的T恤。因此,我不想找到一个学生作为scope方法的输入参数。你知道我如何解决这个问题吗?错误解释 您正在
Tshirt
课堂上调用student
,尽管这是一种即时方法:
joins(:student).where('length < ? AND length > ?', (1.05*self.student.height),(0.95*self.student.height))
然后在控制器方法中提供学员
def index
@tshirts = Tshirt.suitablesize([SOME STUDENT INSTANCE])
end
插入[某个学生实例]
的部分需要是一个学生实例,例如,通过之前请求提供的参数检索
def index
@student = Student.find(params[:id])
@tshirts = Tshirt.suitablesize(@student)
end
确切的参数取决于您的应用程序(除其他外),因此我只能提供一般的指针
选项2:所有学生的衬衫
如果不希望为单个学生找到合适的衬衫,则必须将计算结果放入数据库:
def self.suitable_size
joins(:student)
.where('tshirts.length < 1.05 * students.height AND tshirts.length > 0.95 * students.height')
end
def自身合适的大小
加入(:学生)
.其中('tshirts.length<1.05*students.height和tshirts.length>0.95*students.height')
结束
这将返回属于学生的所有衬衫,其中衬衫长度为学生身高的+/-5%。错误解释 您正在
Tshirt
课堂上调用student
,尽管这是一种即时方法:
joins(:student).where('length < ? AND length > ?', (1.05*self.student.height),(0.95*self.student.height))
然后在控制器方法中提供学员
def index
@tshirts = Tshirt.suitablesize([SOME STUDENT INSTANCE])
end
插入[某个学生实例]
的部分需要是一个学生实例,例如,通过之前请求提供的参数检索
def index
@student = Student.find(params[:id])
@tshirts = Tshirt.suitablesize(@student)
end
确切的参数取决于您的应用程序(除其他外),因此我只能提供一般的指针
选项2:所有学生的衬衫
如果不希望为单个学生找到合适的衬衫,则必须将计算结果放入数据库:
def self.suitable_size
joins(:student)
.where('tshirts.length < 1.05 * students.height AND tshirts.length > 0.95 * students.height')
end
def自身合适的大小
加入(:学生)
.其中('tshirts.length<1.05*students.height和tshirts.length>0.95*students.height')
结束
然后,如果衬衫长度为学生身高的+/-5%,则返回属于学生的所有衬衫。谢谢您的明确解释。我想购买所有适合业主学生的T恤。因此,我不想找到一个学生作为scope的输入参数method@Tolga我更新了答案,加入了关于如何找到所有衬衫的部分,而不仅仅是单个学生的衬衫。谢谢你的明确解释。我想购买所有适合业主学生的T恤。因此,我不想找到一个学生作为scope的输入参数method@Tolga我更新了答案,加入了关于如何查找所有衬衫的部分,而不仅仅是单个学生的衬衫。您不需要使用
Tshirt.all.suitablesize
Tshirt.suitablesize
就足够了,因为它已经返回了一个ActiveRecord作用域,因此all
是一个NoOp。您不需要使用Tshirt.all.suitablesize
Tshirt.suitablesize就足够了,因为它已经返回了一个ActiveRecord作用域,因此all
是一个NoOp。