这些是我遇到问题的模型。
class Admin::FilterGroup < ActiveRecord::Base
has_many :admin_filter_groups_agents,class_name: "Admin::FilterGroupsAgents"
has_many :agents, through: :admin_filter_groups_agents
end
class Admin::FilterGroupsAgents < ActiveRecord::Base
belongs_to :admin_filter_group, :class_name => "Admin::FilterGroup",foreign_key: "admin_filter_group_id"
belongs_to :agent, :class_name => "Agent",foreign_key: "agent_id"
end
class Agent < ActiveRecord::Base
has_many :admin_filter_groups_agents,class_name: "Admin::FilterGroupsAgents"
has_many :admin_filter_groups, through: :admin_filter_groups_agents
end
当我尝试拨打Admin::FilterGroup.first.agents
时,我收到以下错误:
irb(main):001:0> Admin::FilterGroup.first.agents
Admin::FilterGroup Load (0.1ms) SELECT `admin_filter_groups`.* FROM `admin_filter_groups` ORDER BY `admin_filter_groups`.`id` ASC LIMIT 1
Agent Load (63.2ms) SELECT `agents`.* FROM `agents` INNER JOIN `admin_filter_groups_agents` ON `agents`.`id` = `admin_filter_groups_agents`.`agent_id` WHERE `admin_filter_groups_agents`.`filter_group_id` = 1
Mysql2::Error: Unknown column 'admin_filter_groups_agents.filter_group_id' in 'where clause': SELECT `agents`.* FROM `agents` INNER JOIN `admin_filter_groups_agents` ON `agents`.`id` = `admin_filter_groups_agents`.`agent_id` WHERE `admin_filter_groups_agents`.`filter_group_id` = 1
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'admin_filter_groups_agents.filter_group_id' in 'where clause': SELECT `agents`.* FROM `agents` INNER JOIN `admin_filter_groups_agents` ON `agents`.`id` = `admin_filter_groups_agents`.`agent_id` WHERE `admin_filter_groups_agents`.`filter_group_id` = 1
如何解决这个问题?
class CreateAdminFilterGroups < ActiveRecord::Migration
def change
create_table :admin_filter_groups do |t|
t.string :name
t.timestamps
end
end
end
class CreateAdminFilterGroupsAgents < ActiveRecord::Migration
def change
create_table :admin_filter_groups_agents do |t|
t.references :admin_filter_group, index: true
t.references :agent, index: true
t.timestamps
end
end
end
class CreateAgents < ActiveRecord::Migration
def change
create_table :agents do |t|
t.string :name
t.references :user, index: true
t.timestamps
end
end
end
答案 0 :(得分:0)
尝试在Agent
和Admin::FilterGroup
类中同时指定关联另一侧的foreign_key。
所以Agent
:
has_many :admin_filter_groups_agents, class_name: "Admin::FilterGroupsAgents", foreign_key: "agent_id"
对于Admin::FilterGroup
:
has_many :admin_filter_groups_agents,class_name: "Admin::FilterGroupsAgents", foreign_key: "admin_filter_group_id"