Reputation: 1435
I am trying to fetch a column value of last record in Activerecord, from following.
2.2.4 :025 > Equipment.last
Equipment Load (1.0ms) SELECT `equipment`.* FROM `equipment` ORDER BY `equipment`.`id` DESC LIMIT 1
=> #<Equipment id: 7, identifier: "LID-0000007", country_id: 99, state_id: 99, city_id: 99, listing_type: 3, title: "Mix", category_id: 1, sub_category_id: 2, manufacturer_id: 1, model: "ds323", serial_no: "232", year: 2011, condition: 4, other_condition: "", status: 4, other_status: "", price: #<BigDecimal:3d1b1d8,'0.32323E5',9(18)>, weight: nil, weight_units: nil, height: nil, height_units: nil, width: nil, width_units: nil, length: nil, length_units: nil, quantity_available: 1, name_plate_capactiy: nil, name_plate_capactiy_units: "", voltage: "", frequency: nil, phase: nil, current: "", current_units: nil, hours_worked: "", place_of_manufacturing: "", description: "", selling_status: 1, created_at: "2017-02-28 10:15:43", updated_at: "2017-02-28 10:16:30", user_id: 4, wanted_equipment_id: 5, is_read_after_active: false, slug: "mix">
I'm trying to fetch category_id
of the last record.
Equipment.last.pluck(:category_id)
I think I am doing it wrong. Could somebody please tell me. How it is done?
Upvotes: 1
Views: 798
Reputation: 1143
Your method was right. But you need to pluck :category_id
first and then query the last.
Equipment.pluck(:category_id).last
This also works
Equipment.last.try(:category_id)
Upvotes: 2
Reputation: 26
I think you can use:
Equipment.last.try(:category_id)
Because last will give you single record and try will prevent you from the exception if record is not found
Upvotes: 1