我对Rails中的关联有一点问题。
事实上,我有一个Class 播放器,其中has_many 违规属于 SteamServer has_many InfractionTag ,其中belongs_to 代码
我想得到一个播放器的Infraction,服务器以及这个违规的所有标签。我做了:
infractions = Infraction.where(player_steamid64: self.steamid64).includes(:steam_server, :infraction_tags);
但我明白了:
{:infraction_type=>"Ban", :severite=>"Critique", :length=>"01d:00h:00m", :infraction_rp=>"No", :tags=>nil, :steam_server=>#<SteamServer id: 1, name: "Serveur Dev Pure System", ip: "188.165.198.224", ip_query: "188.165.198.224", port: 27015, begin_date: "2015-11-24 00:00:00", reputation: "0,100", reputation_rp: "0,100", accept_new: true, cache: false, validated: true, banner_460: nil, created_at: "2015-11-24 00:00:00", updated_at: "2015-11-24 00:00:00">, :created_at=>"24/11/2015 00:00"}
:tags是nil,但是当我在MySQL中发出这个查询时:
SELECT `infraction_tags`.* FROM `infraction_tags` WHERE `infraction_tags`.`id` IN (1)
我得到了一个结果。
以下是我的模特:
播放器
class Player < ActiveRecord::Base
has_many :infractions, class_name: 'Infraction', primary_key: 'steamid64', foreign_key: 'player_steamid64'
end
违规
class Infraction < ActiveRecord::Base
has_many :infraction_tags
belongs_to :player, class_name: 'Player', foreign_key: 'steamid64'
belongs_to :steam_server, class_name: 'SteamServer', foreign_key: 'id'
end
InfractionTag
class InfractionTag < ActiveRecord::Base
belongs_to :tag
belongs_to :infraction
end
代码
class Tag < ActiveRecord::Base
has_many :infraction_tags
end
SteamServer
class SteamServer < ActiveRecord::Base
end
有人会知道如何以更少的请求获取所有标签? 非常感谢你!
答案 0 :(得分:0)
class Infraction < ActiveRecord::Base
has_many :infraction_tags
has_many :tags, through: :infraction_tags
belongs_to :player, class_name: 'Player', foreign_key: 'steamid64'
belongs_to :steam_server, class_name: 'SteamServer', foreign_key: 'id'
end
来自.includes(:steam_server, :infraction_tags)
到.includes(:steam_server, :tags)