ruby on rails - Object with wrong id after named_scope -


the use case

i have 3 models :

  • a message
  • a conversation
  • a messagerecipient

the relations defined by

  • a message has_and_belongs_to_many conversations (and inversely)
  • a message has_many message_recipients
  • a messagerecipient belongs_to message , recipient (not defined here)

the case works

the method

@recipient.inbox_conversations.first.messages 

create following sql query :

select * `messages` inner join `conversations_messages`   on `messages`.id = `conversations_messages`.message_id (`conversations_messages`.conversation_id = 2061 )  

the result expected message :

[#<message id: 7045, ..>] 

the problem

the next method (just same previous one, additional named scope)

@recipient.inbox_conversations.first.messages.received_by(@recipient) 

create following sql query :

select * `messages` inner join `message_recipients`   on `message_recipients`.message_id = `messages`.id inner join `conversations_messages`   on `conversations_messages`.message_id = `messages`.id (`conversations_messages`.conversation_id = 2060 )   , (`message_recipients`.recipient_id = 32363) 

which returns me inexisting activerecord element

[#<message id: 9025, ..>] 

i tried message.find_by_id(9025) after line, returns nil.

you want additional code ?

class message  named_scope :received_by, lambda { |recipient| {   :conditions => [ "`#{messagerecipient.table_name}`.recipient_id = ?", recipient.id ],   :joins => "inner join `#{messagerecipient.table_name}`    on `#{messagerecipient.table_name}`.message_id = `#{message.table_name}`.id" } } 

.

class receiver  def inbox_conversations   inbox_messages = message.received_by(self).find(:all, :include => :conversations)   return inbox_messages.map(&:conversations).flatten.uniq end 

thanks reading !

the problem rails 2 isn't particularly smart when 2 or more columns in result set have same name: rails looks @ column name these overwrite each other. in case id 1 of joined tables shadowing id messages table.

you need add select option scope either retrieve columns messages table (:select => 'messages.*') or if need columns joined tables select ones need , sure alias conflicting column names.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -