瞄准镜,拉姆达和滑轨3 [英] Scopes, lambda and rails 3

查看:88
本文介绍了瞄准镜,拉姆达和滑轨3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今晚在rails 3中玩示波器,并试图让我了解lambda的作用吗?

having a play with scopes tonight in rails 3, and trying to get my head around what lambda does?

在此示例中,我想要实现的是从与我的食谱模型相关联的国家模型中获取国家名称(:name)的列表.一个食谱属于一个国家,一个国家有很多食谱.

What I am trying to achieve in this example is get a list of country names (:name) from my countries model which is associated with my recipe model. A recipe belongs_to country and a country has many recipes.

我想按照食谱中出现的次数从最高的顺序开始对食谱进行排序.

I would like to order the recipes by amount of times they appear in a recipe, starting with the highest..

所以我正在我的配方模型中尝试此操作(还是应该在国家模型中进行此操作?但是那将行不通,因为我的国家模型已预先填充了世界上每个国家的1个实例)

So i am trying this in my recipe model ( or should I do it within the country model?, but then that wouldn’t work would it as my country model is pre populated with 1 instance of every country in the world)

scope :top_countries, lambda { joins(:countries).merge(Country.name).order("name DESC") }

但是我收到此错误消息

undefined method `default_scoped?' for "Country":String

我的控制器

@toprankingcountry = Recipe.top_countries

很明显,我的理解不是我的想法,希望能获得一些帮助/帮助

obviously my understanding is not what i thought and would appreciate some pointers/assistance

谢谢

推荐答案

我认为问题出在 merge(Country.name)部分. joins(:countries)返回 ActiveRecord :: Relation 实例.其合并方法需要一个参数,该参数是ActievRecord :: Relation的另一个实例,而您合并字符串Country.name.

I believe the problem is with merge(Country.name) part. joins(:countries) returns ActiveRecord::Relation instance. Its merge method expects one argument which is another instance of a ActievRecord::Relation, whereas you merge string Country.name.

一般而言,有效地获得排名靠前的国家列表意味着通过一些附加条件来获得国家(地区)顺序列表.因此,我将这种逻辑应用于国家/地区"模型中.

Generally speaking, getting a list of top countries effectively means getting a list of Countries order by some additional condition. So I'd put this logic into a Country model.

class Country
  has_many :recipes

  def self.top_countries
    joins(:recipes).
      select('countries.*, count(*) AS recipes_count').
      group('countries.id').
      order('recipes_count DESC')
  end
end

此外,如果您使用的RDBMS不能自行找出相关行(例如PostgreSQL< 9.1),则必须手动列出group by子句中的所有列.

Also if you are using RDBMS which cannot figure out dependent rows on its own (like PostgreSQL < 9.1) you'll have to manually list all the columns in group by clause.

从我的国家/地区模型中获取与我的配方模型(实例)相关联的国家/地区名称(:name)列表

get a list of country names (:name) from my countries model which is associated with my recipe model (instance)

我相信无法实现您所说的原样,因为一个国家有很多食谱,反之亦然

I believe it is impossible to achieve what you described as is because a country has_many recipes, not vice versa

这篇关于瞄准镜,拉姆达和滑轨3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆