我的消息模型属于作者和收件人。
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}" }
最佳答案
您不能在单引号中插入变量。
'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/