Rails Associations with dynamic attributes

Hopefully, the table structure at the end is self-explanatory:

I want to be able to do something like this:
@panelist = Panelist.first
puts @panelist.age
$stdout> 30

puts @panelist.gender
$stdout> M

Is this doable through OTB Rails associations (polymorphic or
otherwise), Or
will I have to do some custom coding in order to achieve this?

Thanks

mysql> select * from panel_attribute;
±-------------------±---------------------+
| panel_attribute_id | panel_attribute_name |
±-------------------±---------------------+
| 1 | age |
| 2 | gender |
±-------------------±---------------------+
2 rows in set (0.00 sec)

mysql> select * from panelist;
±------------±--------------+
| panelist_id | panelist_name |
±------------±--------------+
| 1 | user1 |
| 2 | user2 |
±------------±--------------+
2 rows in set (0.00 sec)

mysql> select * from panelist_attribute;
±----------------------±-------------------------±------------±-------------------+
| panelist_attribute_id | panelist_attribute_value | panelist_id |
panel_attribute_id |
±----------------------±-------------------------±------------±-------------------+
| 1 | 30 | 1
| 1 |
| 2 | M | 1
| 2 |
| 3 | 31 | 2
| 1 |
| 4 | F | 2
| 2 |
±----------------------±-------------------------±------------±-------------------+
4 rows in set (0.00 sec)

mysql>

On 18 Aug 2008, at 18:49, Sharad Gupta wrote:

Is this doable through OTB Rails associations (polymorphic or
otherwise), Or will I have to do some custom coding in order to
achieve this?

Well if panelist has_many panelist_attributes then you could easily do
something like

def named_attribute(name)
attribute = panelist_attributes.detect {|a|
a.panel_attribute.panel_attribute_name == name}
attribute ? attribute.panelist_attribute_value : nil
end

You could then hook that through method missing.

You get this to play nicely to rails you should probably rename you
columns to fit the rails conventions. You’ll also save a lot of typing
if you don’t ‘namespace’ your column names.
the above is rather less verbose without these prefixes eg

def named_attribute(name)
attribute = attributes.detect {|a| a.attribute.name == name}
attribute ? attribute.value : nil
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs