下面我给出了我当前的API结果,但是,鉴于执行的SQL,它不是我预期或期望的结果。任何人都可以帮助我获取第二个SQL查询结果而不是第一个吗?
console_game.rb
class ConsoleGame < ActiveRecord::Base
self.table_name = 'console_game'
self.primary_key = :id
has_many :configurations, :class_name => 'Configuration'
end
configuration.rb
class Configuration < ActiveRecord::Base
self.table_name = 'configuration'
self.primary_key = :id
end
resource :configuration do
desc "Finds all configurations associated with a game."
params do
requires :game, type: String, desc: "Game search.", documentation: { example: 'Battlefield 3' }
end
route_param :game do
get do
ConsoleGame.where(value: 'Battlefield 3').includes(:configurations)
end
end
end
D,[2014-05-06T15:11:59.071493#31068] DEBUG - :ConsoleGame加载(0.4ms)SELECT
console_game
。* FROMconsole_game
WHEREconsole_game
。{ {1}} =&#39;战地3&#39; D,[2014-05-06T15:11:59.073289#31068] DEBUG - :配置加载(0.3ms)SELECTvalue
。* FROMconfiguration
WHEREconfiguration
。{{1} IN(2) 127.0.0.1 - - [06 / May / 2014 15:12:08]&#34; GET /配置/游戏HTTP / 1.1&#34; 200 34 25.9740
configuration
console_game_id
注意:此表上有很多外国索引,我想解决所有这些索引,但也许可以解决它们。
[
{
id: 2,
value: "Battlefield 3"
}
]
[
{
id: 2,
value: "x",
device: 4,
system: null,
console_game_id: 2,
creator: "yrdy",
created_date: null,
positive_votes: 0,
negative_votes: 0
},
{
id: 4,
value: "ffds",
system: 2,
console_game_id: 2,
creator: "gdfs",
created_date: null,
positive_votes: 0,
negative_votes: 0
}
]
答案 0 :(得分:1)
这有用吗?
class ConsoleGame < ActiveRecord::Base
#self.table_name = 'console_game'
#self.primary_key = :id
has_many :configurations #, :class_name => 'Configuration'
end
class Configuration < ActiveRecord::Base
#self.table_name = 'configuration'
#self.primary_key = :id
belongs_to :console_game #, class_name: "ConsoleGame", primary_key: 'console_game_id', foreign_key: 'id' #added relationship for ConsoleGame
end
resource :configuration do
desc "Finds all configurations associated with a game."
params do
requires :game, type: String, desc: "Game search.", documentation: { example: 'Battlefield 3' }
end
route_param :game do
get do
#Search Configurations based on console game
Configuration.joins(:console_game).where(console_game:{value: 'Battlefield 3'})
end
end
end
更好的是添加范围
class Configuration < ActiveRecord::Base
#self.table_name = 'configuration'
#self.primary_key = :id
belongs_to :console_game #, class_name: "ConsoleGame", primary_key: 'console_game_id', foreign_key: 'id' #added relationship for ConsoleGame
scope :by_game,->(game){
#verbosely
#game_ids = ConsoleGame.where(value: game).pluck(:id)
#where(console_game_id: game_ids)
#one line
joins(:console_game).where(console_game:{value: game})
}
end
用作
Configuration.by_game('Battlefield 3')
编辑
我已经注释掉了不需要的行,因为它们是由设计隐含的