首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails -更聪明的连接方式?

Rails -更聪明的连接方式?
EN

Stack Overflow用户
提问于 2012-03-23 01:56:36
回答 2查看 90关注 0票数 0

我有这些模型:

代码语言:javascript
复制
class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

class Team < ActiveRecord::Base
  has_many :players_to_teams
  has_many :players, through: :players_to_teams
end

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

球队有运动类型("Football"),球员有主场状态("CA")。

我要一份加州所有橄榄球运动员的名字名单。

SQL将如下所示

代码语言:javascript
复制
SELECT p.FirstName 
FROM players AS p
INNER JOIN players_to_teams AS ptt
ON p.id = ptt.player_id 
INNER JOIN teams AS t 
ON t.id = ptt.team_id 
WHERE t.sport_name = "Football" AND p.home_state = "CA"

我唯一能想到的就是让所有的橄榄球运动员fb_players = Sport.find_all_by_sport_nane("Football"),然后遍历所有的fb_players.players,看看谁来自加利福尼亚,但这感觉比一条SQL语句要慢得多。

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-23 02:06:17

试一试:

代码语言:javascript
复制
Player.select("firstName").joins(:teams).where(:"teams.sport_name" => "Football", :home_state => "CA").map(&:firstName)

要回答您的评论:

.map(&:firstName)就像做.map{ |player| player.firstName }一样。基本上,&将一个Proc转换为一个要传递给map方法的块。但是:firstName不是一个区块?!正确的。但是拼音会自动在符号上调用to_proc方法。

to_proc方法的定义如下:

代码语言:javascript
复制
def to_proc
    proc { |obj, *args| obj.send(self, *args) }
end
票数 1
EN

Stack Overflow用户

发布于 2012-03-23 02:01:51

试试has_and_belongs_to_many

代码语言:javascript
复制
class Player < ActiveRecord::Base
  has_and_belongs_to_many :teams, :join_table = "players_to_teams"
end

class Team < ActiveRecord::Base
  has_and_belongs_to_many :players, :join_table = "players_to_teams"
end

http://jonathanhui.com/ruby-rails-3-model-many-many-association

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9827868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档