Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError: undefined method `pluck' for #<Model>

I am trying to fetch the email id from my User model by joining it with another model called Equipment. The association between two models is as follows:

class Equipment
  belongs_to :user
end

class User
  has_many :equipments
end

The Equipment has a column named identifier So at first I tried fetching the email of a user as follows.

 @email = Equipment.joins(:user).where(identifier: "LID-0000061").pluck(:email)

This worked and gave me the email of the user who added that equipment.

Now I am trying to fetch the email of last added equipment by doing following:

@email = Equipment.joins(:user).last.pluck(:email)

I got:

NoMethodError: undefined method `pluck' for #<Equipment>

My best guess is that I am doing it wrong. Can somebody please tell how do I pluck the email of that last equipment?

like image 260
user3576036 Avatar asked Feb 05 '23 18:02

user3576036


1 Answers

the pluck method works for the ActiveRecord::Relation, not the model itself. when you add the last method, it returns a model instance, so directly visit it's column, no need to use pluck

try this:

@email = Equipment.joins(:user).last.user.email

or

@email = Equipment.joins(:user).pluck(:email).last
like image 102
seaify - Freelancer Avatar answered Mar 13 '23 05:03

seaify - Freelancer