导轨的has_many定制的ActiveRecord协会 [英] Rails has_many custom ActiveRecord Association

查看:93
本文介绍了导轨的has_many定制的ActiveRecord协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个团队模型和灯具模型。灯具模型有一个客队和家庭team.I遵循的例子这个答案并拥有大部分工作的事情。

I have a Teams model and a Fixtures model. The Fixtures model has an away team and a home team.I followed the example in this answer and have most things working.

class Fixture < ActiveRecord::Base
  belongs_to :home, class_name: 'Team'
  belongs_to :away, class_name: 'Team'
end


class Team < ActiveRecord::Base
  has_many :home_games, :class_name => 'Fixture', :foreign_key => 'home_id'
  has_many :away_games, :class_name => 'Fixture', :foreign_key => 'away_id'
end

我希望能够调用@ team.fixtures让所有的球队灯具的名单,目前@ team.home_games给我的家庭灯具和@ team.away_games给我的跳投。 我怎么能写一个的has_many:游戏类似于的has_many:home_games ,并且是最好的方式做到这一点?

I want to be able to call @team.fixtures to get a list of all of the teams fixtures, currently @team.home_games gives me the home fixtures and @team.away_games gives me the aways. How can I write a has_many :games similar to has_many :home_games, and is that the best way to do it?

推荐答案

我认为最好的办法是写的的实例方法为:

I think the best way would be to write an instance method for that:

在组队模式:

def games
  Fixture.where("home_id = ? OR away_id = ?", self.id, self.id)
end

使用它像一个普通的方法:

Use it like a regular method:

Team.first.games
#=> [<Fixture id: ... >, <Fixture id: ... >, ... ]

这应该返回一个ActiveRecord ::关系其中是可以重复使用的作用域链等。

(这里有一个类似的问题,但与 HAS_ONE :<一href="http://stackoverflow.com/questions/307581/rails-model-has-many-with-multiple-foreign-keys">Rails模型的has_many多foreign_keys )

(Here is a similar question, but with has_one: Rails Model has_many with multiple foreign_keys)

另外,你可以从它使用了球队的ID(如果你已经拥有了TEAM_ID而不是团队的实例对象)使类方法:

Also, you could make a class method from it using the id of the Team (if you already have the team_id but not the Team instance object):

class Team < ActiveRecord::Base
  has_many :home_games, :class_name => 'Fixture', :foreign_key => 'home_id'
  has_many :away_games, :class_name => 'Fixture', :foreign_key => 'away_id'

  def games
    Team.games(self.id)
  end

  def self.games(team_id)
    Fixture.where('fixtures.home_id = ? OR fixtures.away_id = ?', team_id, team_id)    
  end
end

和使用这样的:

Team.games(params[:team_id])
# or
@team = Team.where(id: params[:id]).first
@team.games

这篇关于导轨的has_many定制的ActiveRecord协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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