Rails 2.3: how to handle complex joins without writing custom SQL code
I've looked trough the already asked questions but couldn't find an answer.
I've some models:
Each User can cast many Votes, each Vote is linked to one Post, each Post 开发者_C百科can be linked to many Users. Each User can cast only one vote per post.
class User < ActiveRecord::Base
has_many :posts, :through => :user_posts
has_many :user_posts
end
class Vote < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Post < ActiveRecord::Base
has_many :users, :through => :user_posts
has_many :user_posts, :dependent => :destroy
has_many :votes, :dependent => :destroy
end
class UserPost < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
What I'm trying to accomplish is to count how many times "User A" has voted for posts that belongs to "User B" in the last day.
I can do this with a full SQL query but I'd like to know if there is an easied "Rails-friendly way" to perform this.
Thanks!
Augusto
Something like this should work
user_a.votes.count(:conditions => { :post => { :users => user_b }, :date => Date.today }, :joins => { :post => :users })
精彩评论