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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With