Rails 2.3:如何在不编写自定义 SQL 代码的情况下处理复杂的连接
我查看了已经提出的问题,但找不到答案。
我有一些模型:
每个用户可以投很多票,每个投票都链接到一个帖子,每个帖子可以链接到许多用户。每个用户只能为每个帖子投一票。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西应该有效
Something like this should work