[英]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.