当我检索这样的联系人时......
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.province
打电话c.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