ruby on rails - assocition methods on active record relations -


when retrieve contact this...

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

i can't take advantage of association contact has province.rb model, c.province produce no method error.

 contact load (0.2ms)  select "contacts".* "contacts" "contacts"."user_id" = 37 => [#<contact id: 13, firm: "aldjflkads", address: "55 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' #<activerecord::relation:0x007fbe94bd9cf0> 

however, when find contact user id way....

>> c = contact.find_by_user_id(37) 

i can call c.province , c.province.name

 contact load (0.3ms)  select "contacts".* "contacts" "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".* "provinces" "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" 

question: there way can take advantage of association methods if retrieve data this

contact.where(:user_id => 37) 

update

my contact.rb model belongs_to :provinces, however, there's other data (address, postal code etc) that's native contact model. therefore, if did (as suggested in first answer), allow me access province, not of other details need.

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

c = contact.where(:user_id => 37).first.province

where() returns collection.. whereas find_by_id assumes unique result , returns one


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -