-3

@revenue_category is a ActiveRecord object that contains one row from my revenues table which was retrieved with Revenue.all(:order => "revenue_made") and then sorted out. So each of its attributes is a column name, and the value of the attribute is what is stored in that column for that particular row.

@revenue_category looks like this:

--- !ruby/ActiveRecord:Revenue
attributes:
    id: 1
    revenue_made: 3000000
    premium_option_a_cost: 250
    premium_option_b_cost: 450
    premium_option_c_cost: 650

@option_picked looks like this:

    picked_option_(could be a,b or c)_cost

How do I access a particular attribute of an ActiveRecord instance variable when the name of that attribute is stored in another instance variable?

Ryan
  • 5,644
  • 3
  • 38
  • 66
  • where do you need to access the @option_picked? in the view? why not just use an if statement? be a little bit more specific please. – Ionut Hulub Sep 26 '12 at 20:30
  • @IonutHulub right where my comment is in the code.... `@policy_cost = @revenue_category. # <<` I don't know how to get more specific then saying right where I need to access it :( . – Ryan Sep 26 '12 at 20:32
  • what data type is @revenue_category? if it's an array or a hash use @revenue_category[@option_picked] – Ionut Hulub Sep 26 '12 at 20:36

1 Answers1

1

This sounds like you want to dynamically build a message to send to the @option_picked object. Try this and see what happens.

# Given
@option_picked = "a"
lookup = "picked_option_#{ @option_picked }_cost"

# Attributes might be accessible as methods
# depending on the nature of the object...
result = @revenue_category.send(lookup)

# ...or an attribute lookup like this might work
result = @revenue_category[lookup]
Thomas Klemm
  • 10,678
  • 1
  • 51
  • 54
  • unfortunately that's not what I am trying to do at all. I have a value stored in ~@object_picked` and I want to use that value to select an attribute in `@revenue_category`. – Ryan Sep 26 '12 at 20:37
  • See the edit. I think dynamic value lookup is what you are trying to do. – Thomas Klemm Sep 26 '12 at 20:44
  • If I try `@revenue_category.send(lookup)` I get a method missing error and if I use `@revenue_category[lookup]` it doesn't error out but `result` doesn't contain anything. – Ryan Sep 26 '12 at 21:05