MandM
MandM

Reputation: 3383

Ruby on Rails get an attribute from model via api query

The answer to this question should be simple, but I haven't found one through the active record querying guide, other questions here on SO, or through messing around in the Rails console.

I simply want to query the database through the active record querying interface and return the value of a single column of the first or last entry, without having to traverse through the entire table (will explain in a moment).

There is a way to do this with pluck, however the structure of the query messages are as follows:

    initial = Message.where("id = ?", some_id).pluck(:value).first
    final   = Message.where("id = ?", some_id).pluck(:value).last

Unfortunately, this is an extremely inefficient operation as it plucks the value attribute out of every record where there is a match on the provided id, before returning either just the first or last entry. I would like to basically reorder the statements to be something along the lines of:

    initial = Message.where("id = ?", some_id).first.pluck(:value)
    final   = Message.where("id = ?", some_id).last.pluck(:value)

However, I get an NoMethodError explaining there is no method pluck for Message. I've tried to do this various ways:

    initial = Message.where("id = ?", some_id).first(:value)
    initial = Message.where("id = ?", some_id).first.select(:value)
    ...

But all return some sort of error. I know returning the

Oops
Somehow part of my question got cut off (including the answer I had at the end) - I'll see if I can find it, but I explored using the select() method, in which I found that select only takes one argument meaning a query string must be built as it cannot take optional arguments like id = ?, some_id, but then I found that just appending a .value (where value is the column attribute that you are trying to get) works, so I switched back to the where method as shown in the answer below.

Upvotes: 0

Views: 517

Answers (1)

MandM
MandM

Reputation: 3383

Answer is in the question, but if you're trying to do something like this:

    initial = Message.where("id = ?", some_id).pluck(:value).first
    final   = Message.where("id = ?", some_id).pluck(:value).last

Change it to this (just reference the column name, in this example it is value, but it could be amount or something):

    initial = Message.where("id = ?", some_id).first.value
    final   = Message.where("id = ?", some_id).last.value

Upvotes: 2

Related Questions