ruby-on-rails - has_many :messages where user is recipient or author in one query

标签 ruby-on-rails ruby ruby-on-rails-3

我的消息模型属于作者和收件人。

belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_id"
belongs_to :author, :class_name => "User", :foreign_key => "author_id"

现在我想做的是在用户模型中设置一个 has_many 关系,该关系在单个查询中获取所有消息,其中用户是 ether 作者或收件人。我该怎么做?

has_many :messages, :finder_sql => ['author_id = #{self.id} or recipient_id = #{self.id}']

但是这会中断。

  User.first.messages
    User Load (0.6ms)  SELECT "users".* FROM "users" LIMIT 1
    Message Load (0.5ms)  author_id = #{self.id} or recipient_id = #{self.id}
  PGError: ERROR:  syntax error at or near "author_id"
  LINE 1: author_id = #{self.id} or recipient_id = #{self.id}
      ^
:author_id = #{self.id} or recipient_id = #{self.id} ActiveRecord::StatementInvalid:  PGError: ERROR:  syntax error at or near "author_id" LINE 1: author_id = #{self.id} or recipient_id = #{self.id}

更新: 插值变量已从 Rails 3.1 中删除。现在你必须使用 proc

  has_many :messages, :finder_sql => proc { "SELECT * FROM messages WHERE author_id = #{self.id} or recipient_id = #{self.id}" }

source

最佳答案

您不能在单引号中插入变量。

'author_id = #{self.id} or recipient_id = #{self.id}'

应该是

"author_id = #{self.id} or recipient_id = #{self.id}"

关于ruby-on-rails - has_many :messages where user is recipient or author in one query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556251/

相关文章:

ruby-on-rails - 邀请好友邀请系统错误

ruby-on-rails - 使用 HAML 在段落内应用类

ruby-on-rails - PHP 魔术方法 __call、__get 和 __set 的 Ruby 等价物

ruby - 使用 ruby​​ 让 Redis 运行起来

ruby-on-rails - Gemfile gem 安装和 gemspec 依赖

ruby-on-rails - 如何让 Active Job 永远重试所有作业?

ruby-on-rails - 我在 Ubuntu 8.04.4 机器上安装 RVM 失败。我应该将它安装为多用户吗?

javascript - HTML 图像 'onclick' 在调用 javascript 函数时重定向到另一个页面(不需要)

ruby-on-rails - Rails 3 简单的 AJAX 删除不起作用,因为 authenticity_token 没有随请求一起发送

c - rails install pg - 找不到“libpq-fe.h header ”