[英]Rails has_many :through with custom foreign_key
我有以下一組模型:
class Cardstock < ActiveRecord::Base
has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
has_many :palette_colors, :through => :color_matches
end
class ColorMatch < ActiveRecord::Base
belongs_to :palette_color
has_many :cardstocks, :foreign_key => :hex, :primary_key => :hex
end
class PaletteColor < ActiveRecord::Base
has_many :color_matches
has_many :cardstocks, :through => :color_matches
end
調用Cardstock.last.palette_colors
會產生以下錯誤:
ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: character varying = integer
LINE 1: ...".palette_color_id WHERE (("color_matches".hex = 66)) OR...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "palette_colors".* FROM "palette_colors" INNER JOIN "color_matches" ON "palette_colors".id = "color_matches".palette_color_id WHERE (("color_matches".hex = 66)) ORDER BY name ASC
這表明 ActiveRecord 生成的查詢正在使用卡片的 id ( 66
),它應該使用卡片的十六進制 ( bbbbaf
)。 在某處,我需要指定 ActiveRecord 使用hex
列連接cardstocks
和color_matches
。 ActiveRecord 是否支持這個?
你的人際關系在這里完全不正常。
has_and_belongs_to_many
關系has_many relationship
的地方,都需要在對應的 class 中有對應的belongs_to
關系你們建立關系的方式有問題。 我不太了解您在這里的具體用例,所以我不確定問題出在哪里。 考慮這一點的方式可能是多對多的關系。 弄清楚多對多的兩側是什么,連接 model 是什么。 我將舉一個例子,假設 ColorMatch 是您的加入 model - 它是將 PaletteColor 與卡片紙相關聯的原因。 在這種情況下,你會希望你的關系看起來像這樣:
class Cardstock < ActiveRecord::Base
has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
has_many :palette_colors, :through => :color_matches
end
class ColorMatch < ActiveRecord::Base
belongs_to :palette_color
belongs_to :cardstocks, :foreign_key => :hex, :primary_key => :hex
end
class PaletteColor < ActiveRecord::Base
has_many :color_matches
has_many :cardstocks, :through => :color_matches
end
就您的數據庫而言,您應該在color_matches
表上有一個palette_color_id
和一個hex
字段,在cardstocks
表上有一個hex
字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.