我刚发现Active Record的一个奇怪的行为,我不确定我是问题还是活动记录; - )。
我正在使用:Rails 4,Ruby 2.0
这里的模型:
class User < ActiveRecord::Base
has_many :conversation_participants, dependent: :destroy
has_many :conversations, through: :conversation_participants
end
class ConversationParticipant < ActiveRecord::Base
belongs_to :user
belongs_to :conversation
end
class Conversation < ActiveRecord::Base
has_many :conversation_participants, dependent: :destroy
has_many :participants, through: :conversation_participants, source: :user
end
除了has_many :participants
之外还非常简单,source:
指的是User.find(1).conversation_ids
以上的用户。
通常,可以在has_many关联对象上调用collection_singular_ids。就像在这种情况下:
Conversation.find(1).participant_ids
这很有效,我找回了一系列会话ID。但是从另一方面来说:
nil
我总是回来class Conversation < ActiveRecord::Base
has_many :conversation_participants, dependent: :destroy
has_many :users, through: :conversation_participants
end
Conversation.find(1).user_ids
。当我回到has_many的标准时:
SELECT "users".id FROM "users" INNER JOIN "conversation_participants" ON "users"."id" = "conversation_participants"."user_id" WHERE "conversation_participants"."conversation_id" = $1 [["conversation_id", 29]]
会正常工作。
当我查看生成的查询时,我看到原因可能是:
has_many:用户创建:
SELECT "users".* FROM "users" INNER JOIN "conversation_participants" ON "users"."id" = "conversation_participants"."user_id" WHERE "conversation_participants"."conversation_id" = $1 [["conversation_id", 29]]
has_many:参与者创建:
SELECT "users".*
在参与者案例中,我得到了SELECT "users".id
而不是class_name: "User"
(使用{{1}}也没有帮助)
错误或人为错误?