25

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
3
  • Does @medicalhistory.first.lastname work? Commented May 14, 2011 at 21:38
  • not sure if this is "best practice", but @medicalhistory = Medicalhistory.where("user_id = ?", current_user.id)[0] should work Commented May 5, 2013 at 10:27
  • 1
    as a noob, using find instead of where fixed the issues for me Commented Feb 24, 2023 at 15:42

2 Answers 2

46

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I missed first method when looking at the API.
6

One other thing to note, :medicalhistory should be plural as it is a has_many relationship

So your code:

class User < ActiveRecord::Base
  has_many :medicalhistory 
end

Should be written:

class User < ActiveRecord::Base
  has_many :medicalhistories 
end

From the Rails docs (found here)

The name of the other model is pluralized when declaring a has_many association.

This is because rails automatically infers the class name from the association name.

If a user only had_one medicalhistory this would be singular as you had written:

class User < ActiveRecord::Base
  has_one :medicalhistory 
end

I know you already accepted an answer, but thought this would help reduce further errors/confusion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.