关于主动记录关系的关联方法

时间:2013-05-02 19:02:00

标签: ruby-on-rails

当我检索这样的联系人时......

c = Contact.where(:user_id => 37)

我无法利用联系人与Province.rb模型的关联,因为c.province会产生无方法错误。

 Contact Load (0.2ms)  SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = 37
=> [#<Contact id: 13, firm: "aldjflkads", address: "55 SO Avenue", city: "Toronto", postalcode: "M3A B2B", mobile: "999 999 999", office: "", user_id: 37, created_at: "2013-05-02 18:52:01", updated_at: "2013-05-02 18:52:01", province_id: 6>]
>> c.province
NoMethodError: undefined method `province' for #<ActiveRecord::Relation:0x007fbe94bd9cf0>

然而,当我以这种方式通过用户ID找到联系人时....

>> c = Contact.find_by_user_id(37)

然后我可以致电c.provincec.province.name

 Contact Load (0.3ms)  SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = 37 LIMIT 1
=> #<Contact id: 13, firm: "aldjflkads", address: "55 aldjfla;skfj", city: "Toronto", postalcode: "M4G B2B", mobile: "999 999 999", office: "", user_id: 37, created_at: "2013-05-02 18:52:01", updated_at: "2013-05-02 18:52:01", province_id: 6>
>> c.province
  Province Load (0.2ms)  SELECT "provinces".* FROM "provinces" WHERE "provinces"."id" = 6 LIMIT 1
=> #<Province id: 6, name: "Ontario", created_at: "2013-04-19 02:37:11", updated_at: "2013-04-19 02:37:11">
>> c.province.name
=> "Ontario"

问题:如果我检索这样的数据

,我是否有办法利用关联方法
Contact.where(:user_id => 37)

更新

我的Contact.rb模型belongs_to:provinces,但是,其他数据(地址,邮政编码等)是联系人模型的原生数据。因此,如果我这样做(如第一个答案所示),它只允许我访问省份,而不是我需要的任何其他细节。

@contactdetails = Contact.where({:user_id => @user.id}).first.province

1 个答案:

答案 0 :(得分:1)

c = Contact.where(:user_id =&gt; 37).first.province

where()返回一个集合..而find_by_id假定一个唯一的结果,只返回一个