belongs_to 和 foreign_key 不在一个方向上工作
belongs_to with foreign_key not working in one direction
class Position < ActiveRecord::Base
belongs_to :product, foreign_key: :symbol
end
class Product < ActiveRecord::Base
has_many :positions, primary_key: :symbol, foreign_key: :symbol
end
当我做的时候
Product.first.positions.first
我正在取回产品。
但是,当我这样做时 Position.first.product
我一无所获。
当我查看查询生成的SQL时,是:
SELECT "products.*" FROM "products" WHERE "products.id" = ? LIMIT 1 [["id", 0]]
为什么?
试试这个:
class Product < ActiveRecord::Base
self.primary_key = "symbol"
end
生成的 SQL 使用 products.id
而不是 products.symbol
因为你没有告诉它关联应该使用 symbol
作为主键而不是默认值为 id
。因此,在您的 Position
class 中,只需将 primary_key: :symbol
添加到 belongs_to
中,我认为就可以了。
首先,您需要修改模型的创建Product
。
您需要按以下方式创建它:
class CreateProducts < ActiveRecord::Migration
def change
create_table :products, id: false do |t|
t.string :symbol, null: false
t.timestamps
end
add_index :products, :symbol, unique: true
end
end
然后让你的模型知道 primary_key
,那不是 id
:
class Product < ActiveRecord::Base
self.primary_key = "symbol"
end
然后,当您执行 Product.last
时,它将生成以下查询:
Product.last
# Product Load (0.3ms) SELECT "products".* FROM "products" ORDER BY "products"."symbol" DESC LIMIT 1
class Position < ActiveRecord::Base
belongs_to :product, foreign_key: :symbol
end
class Product < ActiveRecord::Base
has_many :positions, primary_key: :symbol, foreign_key: :symbol
end
当我做的时候
Product.first.positions.first
我正在取回产品。
但是,当我这样做时 Position.first.product
我一无所获。
当我查看查询生成的SQL时,是:
SELECT "products.*" FROM "products" WHERE "products.id" = ? LIMIT 1 [["id", 0]]
为什么?
试试这个:
class Product < ActiveRecord::Base
self.primary_key = "symbol"
end
生成的 SQL 使用 products.id
而不是 products.symbol
因为你没有告诉它关联应该使用 symbol
作为主键而不是默认值为 id
。因此,在您的 Position
class 中,只需将 primary_key: :symbol
添加到 belongs_to
中,我认为就可以了。
首先,您需要修改模型的创建Product
。
您需要按以下方式创建它:
class CreateProducts < ActiveRecord::Migration
def change
create_table :products, id: false do |t|
t.string :symbol, null: false
t.timestamps
end
add_index :products, :symbol, unique: true
end
end
然后让你的模型知道 primary_key
,那不是 id
:
class Product < ActiveRecord::Base
self.primary_key = "symbol"
end
然后,当您执行 Product.last
时,它将生成以下查询:
Product.last
# Product Load (0.3ms) SELECT "products".* FROM "products" ORDER BY "products"."symbol" DESC LIMIT 1