需要通过Rails上的has_many带回中间模型和终端模型的信息
我有以下模型:
school.rb
class School < ActiveRecord::Base
has_many :offers
has_many :players, :through => :offers
has_many :teammembers, :class_name => 'Offer', :conditions => ["on_roster = \'t\'"]
has_many :teamplayers, :through => :teammembers, :source => :player
player.rb
class Player < ActiveRecord::Base
has_many :offers, :dependent => :destroy
scope :sr, lambda {
where("(players.year = ? and players.redshirt = 't') or (players.year = ? and players.redshirt = 'f')", (Time.now + 8.months - 5.years).year, (Time.now + 8.months - 4.years).year)
}
Offer.rb
class Offer < ActiveRecord::Base
belongs_to :school
belongs_to :player
validates_uniqueness_of :school_id, :scope => [:player_id]
然后在我的 school_controller 中我有
school_controller.rb
def show
@school = School.find(params[:id], :include => [{:offers => :player}])
@seniors = @school.teamplayers.sr
我的问题是我需要显示优惠模型中的一个字段,该字段与学校和学校之间的关系相关联玩家。目前,我正在视图中执行附加查询来获取此字段。
schools/show.haml.html
- @srpg.each do |player|
= Offer.find_by_school_id_and_player_id(@school.id, player.id).status
显然这会导致 N+1 问题,但我似乎无法找到一种方法来在同一条记录中同时带回 Offer.status 和 player.* 。
I have the following models:
school.rb
class School < ActiveRecord::Base
has_many :offers
has_many :players, :through => :offers
has_many :teammembers, :class_name => 'Offer', :conditions => ["on_roster = \'t\'"]
has_many :teamplayers, :through => :teammembers, :source => :player
player.rb
class Player < ActiveRecord::Base
has_many :offers, :dependent => :destroy
scope :sr, lambda {
where("(players.year = ? and players.redshirt = 't') or (players.year = ? and players.redshirt = 'f')", (Time.now + 8.months - 5.years).year, (Time.now + 8.months - 4.years).year)
}
offer.rb
class Offer < ActiveRecord::Base
belongs_to :school
belongs_to :player
validates_uniqueness_of :school_id, :scope => [:player_id]
Then in my schools_controller I have
schools_controller.rb
def show
@school = School.find(params[:id], :include => [{:offers => :player}])
@seniors = @school.teamplayers.sr
My issue is that I need to display a field from the offers model that is associated to the relationship between the School and the Player. Currently I'm performing an additional query in the view to get this field.
schools/show.haml.html
- @srpg.each do |player|
= Offer.find_by_school_id_and_player_id(@school.id, player.id).status
Obviously this is causing a N+1 issue, but I can't seem to figure out a way to bring back both the offer.status and the player.* in the same record.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
改为使用优惠:
Work with the offers instead: