本文介绍了我如何使用ActiveRecord的查询接口和范围,以确定一个民族的喜爱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模式启动和比赛。

I have two models Starter and Race.

Starter    belongs_to :race
Race       has_many :starters

对于初学者和种族遵循属性:

The attributes for Starter and race follow:

Starter attributes:  id, race_id, finish_position, odds
Race: id, race_date, race_number, field_size

我试图做到两件事:

I'm trying to accomplish two things:

  1. 选择喜欢每场比赛。 #for某一种族的最低赔率入门的*
  2. 选择任何挨打的最爱 *#最喜欢的,有一个finish_position> 1 *
  1. Select the favorite in each race. #for a particular race the Starter with the lowest odds*
  2. Select any beaten favorites *#a favorite that has a finish_position > 1*

确定您的收藏夹和殴打收藏的逻辑是pretty的直线前进(见上文),但我有一个很难翻译成逻辑的ActiveRecord也这是被ActiveRecord的范围可以利用的一个例子。

The logic for determining favorites and beaten favorites is pretty straight forward (see above), but I'm having a hard time translating the logic into activerecord also is this an example were activerecord scopes could be utilized.

下面是我尝试最喜欢的:

Here's my attempt at favorite:

Starter.joins(:赛)。凡(:finish_position =>最低(finish_position))

Starter.joins(:race).where(:finish_position => minimum(finish_position))

这是行不通的,但我还是努力吧。

This isn't working, but I still working at it.

我想,理想的情况是有一个最喜欢的范围和殴打范围。

I guess the ideal would be to have a favorite scope and a beaten scope.

推荐答案

起初一些原则:

  1. 收藏夹和bean_favorites才有意义,当一个种族的存在。因此,他们更是实例方法,而不是类的方法。

  1. The "favorite" and "bean_favorites" only make sense when a race exists. So they are better to be instance methods instead of class methods.

您的种族应该知道的起动的方法不超过一个级别,根据单一职责原则

Your race should know no more than one level of Starter's methods, according Single Responsibility Principle

现在到了code

class Race < ActiveRecord::Base
  def favorite
    starters.lowest_odds
  end

  def beaten_favorite
    starters.finished_lowest_odds
  end
end

class Starter < ActiveRecords::Base
  scope :by_odds, order('odds DESC')
  scope :finished, where('finished_position > 1')

  def lowest_odds
    by_odds.last
  end

  def finished_lowest_odds
    finished.lowest_odds
  end
end

现在要解决的问题

@race.favorite
@race.beaten_favorite

这篇关于我如何使用ActiveRecord的查询接口和范围,以确定一个民族的喜爱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:50