我正在尝试通过以下方式与 rails has_many 创建多对多关系:但是我需要使用不同的列创建关系,而不是使用模型主键(id)。这是我的模型(顺便说一句,我使用的是 Rails 4):
class Food < ActiveRecord::Base
validates :NDB_No, uniqueness: true
validates :NDB_No, :FdGrp_Cd, :Long_Desc, :Shrt_Desc, presence: true
has_many :langual_factor_associations, primary_key: 'NDB_No', foreign_key: 'NDB_No'
has_many :langual_factor_descriptions, through: :langual_factor_associations, primary_key: 'NDB_No', foreign_key: 'NDB_No'
end
class LangualFactorAssociation < ActiveRecord::Base
validates :NDB_No, :Factor_Code, presence: true
belongs_to :food, foreign_key: 'NDB_No'
belongs_to :langual_factor_description, foreign_key: 'Factor_Code'
end
class LangualFactorDescription < ActiveRecord::Base
validates :Factor_Code, uniqueness: true
validates :Factor_Code, :Description, presence: true
has_many :langual_factor_associations, primary_key: 'Factor_Code', foreign_key: 'Factor_Code'
has_many :foods, through: :langual_factor_associations, primary_key: 'Factor_Code', foreign_key: 'Factor_Code'
end
与 LangualFactorAssociation 的 has_many 关联适用于 Food 和 LangualFactorDescription。但是 has_many through: Food 和 LangualFactorDescription 之间的关联不起作用。这是我尝试访问 Food.LangualFactorDescriptions 时遇到的错误:
Food::should create the proper relations to the LangualFactorDescription
model#test_0002_must create the proper associations:
ActiveRecord::StatementInvalid: PG::Error: ERROR: operator does not exist: integer = character varying
LINE 1: ...sociations" ON "langual_factor_descriptions"."id" = "langual...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "langual_factor_descriptions".* FROM "langual_factor_descriptions" INNER JOIN "langual_factor_associations" ON "langual_factor_descriptions"."id" = "langual_factor_associations"."Factor_Code" WHERE "langual_factor_associations"."NDB_No" = $1 ORDER BY "langual_factor_descriptions"."id" ASC LIMIT 1
test/models/food_test.rb:172:in `block (3 levels) in <top (required)>'
我认为问题在于查询的这一部分ON "langual_factor_descriptions"."id" = "langual_factor_associations"."Factor_Code"。我认为设置 primary_key 和/或 foreign_key 选项可以解决这个问题,但事实并非如此。事实上,如果我从模型中删除它们并让它像
has_many :langual_factor_descriptions, through: :langual_factor_associations
rails 产生完全相同的查询,所以在我看来,设置这些选项没有任何作用。我在这里错过了什么吗?关于如何告诉 rails 不要寻找 langual_factor_descriptions.id 而是 langual_factor_descriptions.Factor_Code 的任何想法?
以下是我读过的关于这个主题的一些最相关的资源:http: //guides.rubyonrails.org/association_basics.html
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
has_many :through with :primary_key on join table 不起作用(这几乎是我遇到的问题,但我不确定这是正确的解决方案)