2011-06-06 69 views
2

我有一個叫Person的模型has_one AddressPerson具有first_namelast_name等字段; Addresspostal_code,state等等。使用finders來查詢Rails 3中的引用模型?

我知道如何使用發現者來查找具有某個名字的所有人;那是Person.find_by_last_name("Smith")。但我如何找到所有人:

  • 他們的first_name是「Bob」;和
  • 他們的姓氏是「史密斯」;和
  • 誰與地址與'Foobar'的城市;和
  • 誰擁有的「12345」

回答

1

當你正在尋找確切值POSTAL_CODE地址,你可以把你想匹配where值的哈希值。每個引用的模型都是它自己的嵌套散列,如下例所示:

Person. 
    where(:first_name => 'Bob'). 
    where(:last_name => 'Smith'). 
    where(:address => { :postal_code => '12345' }). # queries associated Address 
    where(:address => { :city => 'Foobar' })   # queries associated Address