Rails5、带聚合作用域
Rails 5, scope with agregation
我有两个模型,产品和图片。
产品有很多图片。
每个图像都有带数字的位置字段。
Product
id | name
1 | Car
Image
id| product_id| file_name | position
1 | 1 | asdad.jpg | 1
1 | 1 | asda.jpg | 2
如何为具有最低位置编号的一张图片创建范围?
scope :main_image, -> { ??? }
比:
@product.main_image.image.url
问候
塞巴
你实际上不需要范围,你需要名为 main_image
:
的方法
def main_image
images.order(:position).first
end
我有两个模型,产品和图片。 产品有很多图片。 每个图像都有带数字的位置字段。
Product
id | name
1 | Car
Image
id| product_id| file_name | position
1 | 1 | asdad.jpg | 1
1 | 1 | asda.jpg | 2
如何为具有最低位置编号的一张图片创建范围?
scope :main_image, -> { ??? }
比:
@product.main_image.image.url
问候 塞巴
你实际上不需要范围,你需要名为 main_image
:
def main_image
images.order(:position).first
end