我有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
课程以及Game
和Person
课程的最佳方法是什么?
我正在使用Rails v4.2.6
答案 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