简体   繁体   English

Rails:使用自定义方法订购自定义模型

[英]Rails: Order custom model using custom method

I have a custom model called product, and it has many reviews. 我有一个名为product的自定义模型,并且有很多评论。

i have a method that calculates the review 我有一种计算评论的方法

def rating
    total = 0
    reviews_count = reviews.count

    return 0 if reviews_count == 0

    reviews.each do |review|
        total += review.grade
    end

    total.to_f/reviews_count
end

i would like to know how could i use this method to Order my products. 我想知道如何使用这种方法订购产品。

At products_controller.rb, if i use: 在products_controller.rb,如果我使用:

@products = Product.all.order("price")

its easy, it gives me the products list ordered by price. 这很容易,它给了我按价格排序的产品清单。 But, if i use, for example: 但是,如果我使用例如:

@products = Product.all.sort_by{|p| p.rating}

it gives me an array and not a "ActiveRecord::Relation" 它给了我一个数组,而不是一个“ ActiveRecord :: Relation”

I would like to know how could i order my product using a custom method that returns a value. 我想知道如何使用返回值的自定义方法订购产品。

In general, you can't. 一般来说,您不能。 Ordering happens in your database, which has no knowledge about any method you typed in your application. 排序在数据库中进行,该数据库不了解您在应用程序中键入的任何方法。 What you need is a way of translating your method into a valid sql. 您需要的是一种将方法转换为有效sql的方法。 In your case, you can do: 就您而言,您可以执行以下操作:

Product.joins(:reviews).group('products.id').order('AVG(reviews.grade)')

That will give you sorted results and the relation object. 这将为您提供排序结果和关系对象。 However, relations with join are not that nice to work with, especially if you try to add another join. 但是,与联接的关系不太好使用,尤其是当您尝试添加另一个联接时。 Also this might get quite slow when your database grows. 另外,当数据库增长时,这可能会变得很慢。

What you're doing in your example is running the query then using sort_by to sort the result set. 在示例中,您正在执行的操作是运行查询,然后使用sort_by对结果集进行排序。

If you want to get back an activerecord collection instead of an array, and potentially chain this with other scopes, you should move the logic from your method into SQL, and put it in a scope. 如果要获取一个activerecord集合而不是一个数组,并可能将其与其他作用域链接起来,则应将逻辑从方法移到SQL中,并将其放在作用域中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM