我无法绕过更高级的Rails查询方法。在这种情况下,我有三个表:用户,友谊和事件。
我已在每个
的模型中进行如下设置用户 - > :has_many => :friendships,:has_many => :项目
Friendship-> :belongs_to => :用户
事件 - > belongs_to => :用户
友谊只是两列:“user_id”和“friend_id”,所以每个新友谊都会创建两个新行。
这是我用来查找“属于current_user的朋友的前四个事件的查询,其中start_date比现在晚了。”
find_by_sql(["SELECT DISTINCT e.id
FROM events e
WHERE e.start_date > ?
AND e.user_id IN(
SELECT f.user_id
FROM friendships f
WHERE f.friend_id = ?)
LIMIT 0,4", Time.zone.now,current_user.id])
在Rails中做这样的事情的真实而优雅的方法是什么?我觉得这也是非常低效的......
答案 0 :(得分:5)
您应该可以使用:join
和:conditions
time_range = (Time.now.midnight - 4.days)..Time.now.midnight
Event.all :joins => :friendships, :conditions =>
{'start_date' => time_range, 'friendships.friend_id' => current_user.id}, :limit => 4
我并没有像这样做过很多复杂的查询,但是我从这里的示例拼凑了这些:http://guides.rubyonrails.org/active_record_querying.html
编辑: 您可能需要添加到事件:
has_many :friends, :through => :friendships
Edit2:看起来你必须实际使用嵌套连接:
Event.all :joins => {:user => :friendships }, :conditions => {'start_date' => time_range, 'friendships.friend_id' => current_user.id }
以下是我使用的型号代码:
class User < ActiveRecord::Base
has_many :events, :foreign_key => "user_id"
has_many :friendships
has_many :friends, :through => :friendships, :source => :user, :uniq => true
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :friendships, :through => :user
end
class Friendship < ActiveRecord::Base
belongs_to :user
end
并且,如果可能有帮助,可以输出一些示例:
>> Event.all :joins => {:user => :friendships }, :conditions => {'happens_on' => time_range, 'friendships.user_id' => 1 }
Event.all :joins => {:user => :friendships }, :conditions => {'happens_on' => time_range, 'friendships.user_id' => 1 }
=> [#<Event id: 1, happens_on: "2010-08-06 00:42:37", title: "Jims party", description: "Happy Birthday", created_at: "2010-08-03 00:42:37", updated_at: "2010-08-03 00:42:37", user_id: 1>]
>> jim = User.find(1)
jim = User.find(1)
=> #<User id: 1, name: "Jim", bio: "Loves Rails", age: 30, created_at: "2010-08-03 00:30:51", updated_at: "2010-08-03 00:30:51">
>> crystal = User.find(2)
crystal = User.find(2)
=> #<User id: 2, name: "Crystal", bio: "Loves writing", age: 26, created_at: "2010-08-03 00:31:14", updated_at: "2010-08-03 00:31:14">
>> jim.events
jim.events
=> [#<Event id: 1, happens_on: "2010-08-06 00:42:37", title: "Jims party", description: "Happy Birthday", created_at: "2010-08-03 00:42:37", updated_at: "2010-08-03 00:42:37", user_id: 1>]
>> event1 = jim.events[0]
event1 = jim.events[0]
=> #<Event id: 1, happens_on: "2010-08-06 00:42:37", title: "Jims party", description: "Happy Birthday", created_at: "2010-08-03 00:42:37", updated_at: "2010-08-03 00:42:37", user_id: 1>
>> event1.user
event1.user
=> #<User id: 1, name: "Jim", bio: "Loves Rails", age: 30, created_at: "2010-08-03 00:30:51", updated_at: "2010-08-03 00:30:51">
>> event1.friendships
event1.friendships
=> [#<Friendship user_id: 1, friend_id: nil, created_at: "2010-08-03 00:57:31", updated_at: "2010-08-03 00:57:31">]
>>