Rails 2.3:如何在不编写自定义 SQL 代码的情况下处理复杂的连接

发布于 2024-10-30 08:33:12 字数 717 浏览 1 评论 0原文

我查看了已经提出的问题,但找不到答案。

我有一些模型:

每个用户可以投很多票,每个投票都链接到一个帖子,每个帖子可以链接到许多用户。每个用户只能为每个帖子投一票。

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

我想要完成的是计算“用户 A”在最后一天为属于“用户 B”的帖子投票的次数。

我可以使用完整的 SQL 查询来完成此操作,但我想知道是否有一种简单的“Rails 友好方式”来执行此操作。

谢谢!

奥古斯托

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 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南巷近海 2024-11-06 08:33:12

像这样的东西应该有效

user_a.votes.count(:conditions => { :post => { :users => user_b }, :date => Date.today }, :joins => { :post => :users })

Something like this should work

user_a.votes.count(:conditions => { :post => { :users => user_b }, :date => Date.today }, :joins => { :post => :users })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文