Ruby on Rails: undefined method `user' for #<ActiveRecord::Relation::ActiveRecord_Relation_User:0x4451148>

StackOverflow https://stackoverflow.com/questions/21752407

  •  11-10-2022
  •  | 
  •  

문제

The code is below. User is the name in my database, but it is saying it is an undefined method when it should not be. It is just a string value in my database. I have looked at all the other posts about this error but their solutions did not work for me. (I used scaffold btw so I don't know if that affects anything)

  def self.login(user, password)
    the_user = self.where(user: user, password:password)
    if the_user.empty?
      return ERR_BAD_CREDENTIALS
    else
      return the_user.user
    end
  end
도움이 되었습니까?

해결책

this line:

the_user = self.where(user: user, password:password)

should be:

the_user = self.where(user: user, password:password).first

without the the .first what you get is a relation object, which can be used to chain further .where clauses to it (or similar methods). You must use .first or something like each on it to actually get records from the database.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top