Rails多态连接has_many,通过返回不可能的SQL

时间:2016-08-11 23:20:32

标签: ruby-on-rails polymorphic-associations

我有3个模型设置如下:

class User < ActiveRecord::Base

  has_many :interests, as: :interesting, dependent: :destroy
  has_many :games, through: :interests, source: :interesting, source_type: 'Game'
  has_many :people, through: :interests, source: :interesting, source_type: 'Person'

end

class Interest < ActiveRecord::Base

  belongs_to :interesting, polymorphic: true
  validates :user_id, presence: true
  validates :interesting_id, presence: true
end

class Game < ActiveRecord::Base
   has_many :users, through: :interests
   has_many :interests, as: :interesting
end

class Person < ActiveRecord::Base

  has_many :users, through: :interests
  has_many :interests, as: :interesting

end

当我尝试调用user.games时,数据库上的SQL运行是

SELECT "games".* FROM "games" 
INNER JOIN "interests" 
ON "game"."id" = "interests"."interesting_id" 
WHERE "interests"."interesting_id" = $1 AND
    "interests"."interesting_type" = $2 AND
    "interests"."interesting_type" = $3  
[["interesting_id", 3], 
["interesting_type", "User"], 
["interesting_type", "Game"]]

所以很明显没有回复。只要不包含["interesting_type", "User"],查询就应该有效。

我做错了什么?设置User课程以及GamePerson课程的最佳方法是什么?

我正在使用Rails v4.2.6

2 个答案:

答案 0 :(得分:1)

总而言之,以下似乎适用于此用例:

User < ActiveRecord::Base 
  has_many :interests, dependent: :destroy 
  has_many :games, through: :interests, 
           source: :interesting, source_type: 'Game'
  has_many :people, through: :interests, 
           source: :interesting, source_type: 'Person'

end

class Interest < ActiveRecord::Base
  belongs_to :user
  belongs_to :interesting, polymorphic: true
  validates :user_id, presence: true 
  validates :interesting_id, presence: true 
end

答案 1 :(得分:0)

请尝试这个

class User < ActiveRecord::Base

  has_many :interests, dependent: :destroy
  has_many :games, as: :interesting, through: :interests, source_type: 'Game'
  has_many :people, as: :interesting, through: :interests, source_type: 'Person'

end

class Interest < ActiveRecord::Base

  belongs_to :interesting, polymorphic: true
  validates :user_id, presence: true # I don't know the reason to use that if you use as polymorphic 
  validates :interesting_id, presence: true 
end

table_name interests它应该只有:id:, :interesting_id, :interesting_type

属性