【问题标题】:undefined column in rails many to many导轨中的未定义列多对多
【发布时间】:2015-07-23 02:09:32
【问题描述】:

所以我在我的 2 个模型之间定义了一个 has_and_belongs_to_many 关系,如下所示

class Client < ActiveRecord::Base
  attr_accessible  :first_name, :last_name, :email
  has_and_belongs_to_many :themes, class_name: 'XY::Theme'
end

class XY::Theme < ActiveRecord::Base      
  has_and_belongs_to_many  :clients
end

然后我像这样从活动记录导轨指南中定义了我的连接表

class CreateClientsThemesJoinTable < ActiveRecord::Migration
  def change
    create_table :clients_xy_themes, id: false do |t|
        t.integer :client_id
        t.integer :xy_theme_id
    end
    add_index :clients_xy_themes, :client_id
    add_index :clients_xy_themes, :xy_theme_id
  end
end

但是当我尝试从 rails 控制台中的客户端表访问主题时,我得到了这个错误

PG::UndefinedColumn: ERROR:  column clients_xy_themes.theme_id does not exist
LINE 1: ...ER JOIN "clients_xy_themes" ON "xy_themes"."id" = "clients_v...

为什么会这样?我的迁移特别说明了主题表上的键,但它试图访问一个不存在的列

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    约定是,如果您的关系名称是themes,那么外键名称就是theme_id

    你可以这样定义关系:

    has_and_belongs_to_many :xy_themes, class_name: 'XY::Theme'
    

    或者您必须定义association_foreign_key 选项。

    has_and_belongs_to_many :themes, class_name: 'XY::Theme', association_foreign_key: 'xy_theme_id'
    

    【讨论】:

    • 谢谢!定义外国协会有效!
    • 我又遇到了更多麻烦,如果我尝试通过执行theme.clients 从主题转到客户端,它会给我与上述主题ID 相同的错误。我尝试将 Association_foreign_key "client_id" 用于主题,但它不起作用。建议?
    • @ApprenticeProgrammer 尝试使用foreign_key: 'xy_theme_id'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2017-12-15
    • 2021-07-19
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多