Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord, Find by value of nested attribute

I have a Phone model nested to Message model. How can I find all Messages by a given number considering that number attribute is inside Phone model and not in Message?

This is what I currently got

class Message < ActiveRecord::Base
   attr_accessible  :phone_id
   belong_to :phone
end

class Phone < ActiveRecord::Base
   attr_accessible  :phone
   has_many :messages
end
like image 257
Martin Avatar asked May 25 '12 17:05

Martin


2 Answers

Message.joins(:phone).where(phones: { phone: '555-555-5555' })
like image 55
Nick Colgan Avatar answered Oct 12 '22 14:10

Nick Colgan


Message.joins(:phone).where("phones.phone = ?","123-456-7890").all
like image 23
klochner Avatar answered Oct 12 '22 16:10

klochner