小编mga*_*dda的帖子

rails 3 has_many通过has_one

假设您有以下型号:

class Category < ActiveRecord::Base
  has_one :current_heat, class_name: 'Heat'
  has_many :scores, :through => :current_heat
end

class Heat < ActiveRecord::Base
  belongs_to :category
  has_many :scores
end

class Score < ActiveRecord::Base  
  belongs_to :heat
end
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,当我调用Category.first.scoresActiveRecord时会产生以下查询:

SELECT `categories`.* FROM `categories` LIMIT 1
SELECT * FROM `scores` INNER JOIN `heats` ON `scores`.`heat_id` = `heats`.`id` WHERE `heats`.`category_id` = 1
Run Code Online (Sandbox Code Playgroud)

上面的查询忽略了has_one的性质Category#current_heat.我原本期待的更像是:

SELECT `categories`.* FROM `categories` LIMIT 1
SELECT `heats`.* FROM `heats` WHERE `heats`.`category_id` = 1 LIMIT 1
SELECT * FROM `scores` WHERE `scores`.`heat_id` …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails has-many-through

4
推荐指数
1
解决办法
2512
查看次数