Rails has_many:通过自定义foreign_key

Ale*_*ahn 5 sql activerecord ruby-on-rails has-many-through

我有以下一套模型:

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
Run Code Online (Sandbox Code Playgroud)

调用会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
Run Code Online (Sandbox Code Playgroud)

这告诉我ActiveRecord生成的查询是使用cardstock的id(66),它应该使用cardstock的hex(bbbbaf).在某个地方,我需要指定ActiveRecord使用hex列来连接cardstockscolor_matches.ActiveRecord是否支持此功能?

jef*_*unt 2

你们的关系在这里完全不正常。

  • Cardstock 和 ColorMatch 之间的关系应该是has_and_belongs_to_many双方的关系
  • 凡是有 a 的地方has_many relationship,都需要belongs_to在对应的类中存在对应关系

  • 这不完全正确。使用 `has_many :through` 而不是 `has_and_belongs_to_many` 绝对没有问题;我相信这甚至是当今的首选方式。然而,你的观点是正确的,关系中存在问题。 (4认同)