我想創建一個多對多的關係與軌道has_many通過:但不是使用模型主鍵(id)我需要使用不同的列創建關係。 這裏是我的模型(順便說一句,我使用Rails 4):Rails has_many:通過與:primary_key
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工作正常用於食品和LangualFactorDescription。但has_many通過: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
導軌產生完全相同的查詢,所以在我看來,設置這些選項不做任何事。我在這裏錯過了什麼嗎?任何想法如何我可以告訴軌道不尋找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 not working(其實這就是我有問題,但我不知道這是正確的解決方案)
Rails has_many association with multiple keys
https://www.ruby-forum.com/topic/139765
Has Many Through Alternative Primary and Foreign Keys
我不確定,您可以嘗試在模型LangualFactorDescription中使用self.primary_key ='Factor_Code' – yxf
好吧!但我有一個問題:即使DB中的主鍵仍然是id,是否可以將該字段定義爲模型中的主要字段? – Jose
我認爲這是好的,我認爲'primary_key'告訴ActiveRecord哪個字段將用於連接另一個表。 – yxf