simplytrue
simplytrue

Reputation: 59

How to get a attribute from an instance of an ActiveRecord relation

I am using the following to try to return a value from my database.

rate = @table_selection.constantize.where(age: quote_profile.age, risk_profile =>  true)

I am using variables to look up the value age is one and the risk_profile is a variable that contains a string representing the column name of "standard_rate" stored as a decimal. I am trying to lookup the value. Age is unique in the database.

However instead of the value I am getting this returned:

'Rate::ActiveRecord_Relation:0x007fe357c7a528' 

which is what I am asking for with the 'where'.

How can I get the actual value from the column I am referencing in the where clause? I need this because I want to use the rate as an input to a create action...

schema table:

create_table "ten_year_term_rates", force: :cascade do |t|
    t.integer  "age"
    t.decimal  "standard_rate"
    t.decimal  "premium_rate"
    t.datetime "created_at",                         null: false
    t.datetime "updated_at",                         null: false
end

Upvotes: 0

Views: 2369

Answers (3)

Nikita Misharin
Nikita Misharin

Reputation: 2020

As '#pluck' doesn't work for you, try to use method #map. It will give return array of values that you can use later on.

rate = @table_selection.constantize.where(age: quote_profile.age, risk_profile =>  true).map { |record| record.send risk_profile }

Upvotes: 1

simplytrue
simplytrue

Reputation: 59

I found a solution but had to do it without the where clause. Here is the code:

 rate_record = @table_selection.constantize.find_by(age: quote_profile.age)

The find_by statement gets the number (data) I am looking for then I call

 rate = rate_record.send(risk_profile)

which is a way to call a method when using a variable. I got the idea from this answer on here: Can you use variables to reference table columns in Rails?

Not sure why find_by works and where does not if anyone has a better solution that can be done in one line I am all for it...

Upvotes: 0

Anand
Anand

Reputation: 6531

rate = @table_selection.constantize.where("age = ? OR risk_profile = ?", quote_profile.age, true)

Upvotes: 0

Related Questions