[英]Rails3 has_many :through and foreign_key not work in set :class_name
Hi, all 大家好
I need find friends activities: 我需要寻找朋友的活动:
SELECT `activities`.* FROM `activities`
INNER JOIN `friendships`
ON `activities`.user_id = `friendships`.friend_id
WHERE ((`friendships`.user_id = 1))
My add this code to User Model: 我将此代码添加到用户模型:
has_many :friends_activities,
:class_name => 'Activity',
:through => :friendships,
:foreign_key => :user_id,
:source => :friend
But Rails return is: 但是Rails的回报是:
SELECT `activities`.* FROM `activities`
INNER JOIN `friendships`
ON `activities`.id = `friendships`.friend_id
WHERE ((`friendships`.user_id = 1))
I need : 我需要 :
`activities`.user_id = `friendships`.friend_id
But Now: 但现在:
`activities`.id = `friendships`.friend_id
PS: My Tables: PS:我的桌子:
create_table "activities", :force => true do |t|
t.integer "user_id"
t.integer "target_id"
t.string "target_type"
t.string "verb"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "friendships", :force => true do |t|
t.integer "user_id", :null => false
t.integer "friend_id", :null => false
t.string "state"
t.datetime "created_at"
t.datetime "updated_at"
end
I am not sure you can use the additional options on the has_many :through. 我不确定您是否可以在has_many:through上使用其他选项。 According to the docs :
根据文档 :
Specifies an association through which to perform the query.
指定通过其执行查询的关联。 This can be any other type of association, including other :through associations.
这可以是任何其他类型的关联,包括其他:through关联。 Options for :class_name, :primary_key and :foreign_key are ignored , as the association uses the source reflection.
:class_name,:primary_key和:foreign_key的选项将被忽略 ,因为关联使用源反射。
[emphasis mine] [强调我的]
Your last resort might be: 您最后的选择可能是:
has_many :friends_activities,
:class_name => 'Activity',
:finder_sql => Proc.new {
%Q{
SELECT `activities`.* FROM `activities`
INNER JOIN `friendships`
ON `activities`.user_id = `friendships`.friend_id
WHERE ((`friendships`.user_id = #{id}))
}
}
I'm sure there is a more elegant way to achieve this, but in the meantime this should do the work. 我敢肯定,有一个更优雅的方法可以实现这一目标,但与此同时,这应该可以完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.