:订单不起作用:include

时间:2010-12-30 02:51:00

标签: ruby-on-rails

我想知道为什么这会给我一个错误:

DiscoveredLocation.find_all_by_user_id(user.id, :include => [:boss_location, :monsters], :order => 'boss_location.location_index ASC')

好像它正在尝试执行一个非常长的查询,我得到一个错误,如:

Mysql::Error: Unknown column 'monsters_discovered_locations_join.boss_location_id' in 'on clause': SELECT `discovered_locations`.`id` AS t0_r0, `discovered_locations`.`user_id` AS t0_r1, `discovered_locations`.`boss_location_id` AS t0_r2, `discovered_locations`.`created_at` AS t0_r3, `discovered_locations`.`updated_at` AS t0_r4, `boss_locations`.`id` AS t1_r0, `boss_locations`.`name` AS t1_r1, `boss_locations`.`location_index` AS t1_r2, `boss_locations`.`min_level` AS t1_r3, `boss_locations`.`needed_gold_to_open` AS t1_r4, `boss_locations`.`created_at` AS t1_r5, `boss_locations`.`updated_at` AS t1_r6, `monsters`.`id` AS t2_r0, `monsters`.`name` AS t2_r1, `monsters`.`strength` AS t2_r2, `monsters`.`dexterity` AS t2_r3, `monsters`.`magic` AS t2_r4, `monsters`.`accuracy` AS t2_r5, `monsters`.`minGold` AS t2_r6, `monsters`.`maxGold` AS t2_r7, `monsters`.`hp` AS t2_r8, `monsters`.`level` AS t2_r9, `monsters`.`armor` AS t2_r10, `monsters`.`first_class` AS t2_r11, `monsters`.`weapon_id` AS t2_r12, `monsters`.`imageName` AS t2_r13, `monsters`.`monster_type` AS t2_r14, `monsters`.`boss_location_index` AS t2_r15, `monsters`.`boss_location_id` AS t2_r16, `monsters`.`created_at` AS t2_r17, `monsters`.`updated_at` AS t2_r18 FROM `discovered_locations`  LEFT OUTER JOIN `boss_locations` ON `boss_locations`.id = `discovered_locations`.boss_location_id  LEFT OUTER JOIN `boss_locations` monsters_discovered_locations_join ON (`discovered_locations`.`id` = `monsters_discovered_locations_join`.`boss_location_id`)  LEFT OUTER JOIN `monsters` ON (`monsters`.`boss_location_id` = `monsters_discovered_locations_join`.`id`) WHERE (`discovered_locations`.`user_id` = 986759322)  ORDER BY boss_location.location_index ASC

模型关联是:

class BossKill < ActiveRecord::Base

    belongs_to :user
    belongs_to :monster

class DiscoveredLocation < ActiveRecord::Base
  belongs_to :user
  belongs_to :boss_location

  has_many :monsters, :through => :boss_location

  has_many :boss_kills, :through => :monsters

class BossLocation < ActiveRecord::Base

  has_many :discovered_locations
  has_many :users, :through => :discovered_locations

  has_many :monsters

class Monster < ActiveRecord::Base
  belongs_to :boss_location

  has_many :boss_kills

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

正确...因为包括INCLUDES - 它使用激进的加载,与连接不同。这里的行为没有任何问题。更改:包括:加入,您将获得所需的结果,但效率较低

DiscoveredLocation.find(
    :all, 
    :conditions => {
        :user_id => user.id
    }, 
    :joins => :boss_locations, 
    :include => :monsters, 
    :order => 'boss_locations.location.index'
)

尝试 - 记住 - 模型名称是单数,但TABLE名称是复数(boss_location vs boss_locations)。如果你阅读了你的日志/错误,你会看到这个