【问题标题】:Rails has_many :through with custom foreign_keyRails has_many:通过自定义foreign_key
【发布时间】:2011-09-13 23:45:52
【问题描述】:

我有以下一组模型:

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 支持吗?

【问题讨论】:

  • 顺便说一下,这是 Rails 2.3.x。

标签: sql ruby-on-rails activerecord has-many-through


【解决方案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

就您的数据库而言,color_matches 表上应该有一个palette_color_id 和一个hex 字段,cardstocks 表上应该有一个hex 字段。

【讨论】:

  • 没错!但是,在这样设置我的关联之后,我仍然遇到同样的错误。 ActiveRecord 支持这个吗?还是我需要为十六进制设置另一个表,cardstockscolor_matches 都将指向整数列?
【解决方案2】:

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

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

【讨论】:

  • 这并不完全正确。使用has_many :through 而不是has_and_belongs_to_many 绝对没有错;我相信这甚至是这些天的首选方式。但是,您的关系有问题是正确的。
  • 谢谢,我需要将 ColorMatches 中的 has_many 调用更改为 belongs_to。但我认为还有更多问题,因为仍然会生成错误的查询。
猜你喜欢
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多