undefined method for ActiveRecord::Relation

后端 未结 2 478
感动是毒
感动是毒 2020-12-28 15:39

User model

class User < ActiveRecord::Base
  has_many :medicalhistory 
end

Mdedicalhistory model

class Medicalhistory &l         


        
相关标签:
2条回答
  • 2020-12-28 16:07

    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.

    0 讨论(0)
  • 2020-12-28 16:24

    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.

    0 讨论(0)
提交回复
热议问题