undefined method for ActiveRecord::Relation
activerecord, ruby-on-rails-3
Solution
Well, you are getting back an object of `ActiveRecord::Relation`, not your model instance, thus the error since there is no method called `lastname` in `ActiveRecord::Relation`.
Doing `@medicalhistory.first.lastname` works because `@medicalhistory.first` is returning the first instance of the model that was found by the `where`.
Also, you can print out `@medicalhistory.class` for both the working and "erroring" code and see how they are different.
Problem
User model ``` class User < ActiveRecord::Base has_many :medicalhistory end ``` Mdedicalhistory model ``` class Medicalhistory < ActiveRecord::Base belongs_to :user #foreign key -> user_id accepts_nested_attributes_for :user end ``` Error ``` undefined method `lastname' for #<ActiveRecord::Relation:0xb6ad89d0> #this works @medicalhistory = Medicalhistory.find(current_user.id) print "\n" + @medicalhistory.lastname #this doesn't! @medicalhistory = Medicalhistory.where("user_id = ?", current_user.id) print "\n" + @medicalhistory.lastname #error on this line ```