【问题标题】:Rails 2.3: how to handle complex joins without writing custom SQL codeRails 2.3:如何在不编写自定义 SQL 代码的情况下处理复杂的连接
【发布时间】:2011-04-04 22:21:58
【问题描述】:

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

我有一些模型:

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

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 友好方式”来执行此操作。

谢谢!

奥古斯托

【问题讨论】:

  • 什么是 UserPost 模型?你为什么拥有它?如何确定帖子是否属于用户?
  • UserPost 模型是:类 UserPost
  • 所以一个帖子可以属于多个用户。对吗?
  • @潘:对! @post.users 输出其用户数组。

标签: ruby-on-rails activerecord join


【解决方案1】:

这样的东西应该可以工作

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

【讨论】:

  • 顺便问一下,你知道一些在线资源,我可以在其中找到一些关于如何在 Rails 中构建连接查询的好文档吗?
猜你喜欢
  • 2010-10-03
  • 2023-04-02
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多