Rails has_many:通过自定义foreign_key

时间:2011-06-13 14:44:36

标签: sql ruby-on-rails activerecord 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

调用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是否支持此功能?

2 个答案:

答案 0 :(得分:2)

你们的关系在这里完全没有了。

  • Cardstock和ColorMatch之间的关系双方应该是has_and_belongs_to_many关系
  • 只要您有has_many relationship,就需要在相应的班级中找到相应的belongs_to关系

答案 1 :(得分:1)

你的人际关系建立方式有问题。我不太明白你的具体用例,所以我不确定问题出在哪里。思考这个问题的方式可能是多对多的关系。弄清楚多对多的两个方面是什么,以及连接模型是什么。我将举一个例子,假设ColorMatch是你的连接模型 - 它是PaletteColor与Cardstock的关系。在这种情况下,您希望您的关系看起来像这样:

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

就您的数据库而言,palette_color_id表上应有hexcolor_matches字段,hex上有cardstocks字段表

相关问题