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列来连接cardstocks和color_matches.ActiveRecord是否支持此功能?
你们的关系在这里完全不正常。
has_and_belongs_to_many双方的关系has_many relationship,都需要belongs_to在对应的类中存在对应关系