簡體   English   中英

Rails has_many:through with custom foreign_key

[英]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列連接cardstockscolor_matches ActiveRecord 是否支持這個?

你的人際關系在這里完全不正常。

  • Cardstock 和 ColorMatch 之間的關系應該是雙方的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM