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


my message model belongs_to author , recipient.

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

now setting has_many relationship in user model getting messages user ether author or recipient in single query. how do that?

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

however breaks.

  user.first.messages     user load (0.6ms)  select "users".* "users" limit 1     message load (0.5ms)  author_id = #{self.id} or recipient_id = #{self.id}   pgerror: error:  syntax error @ 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 @ or near "author_id" line 1: author_id = #{self.id} or recipient_id = #{self.id} 

update: interpolating variables removed rails 3.1. have use proc

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

source

you cannot interpolate variables in single quotes.

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

should be

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

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -