Rails 3: Hash accessor in the model? -
i'm struggling stretch understanding of basic rails concepts beyond tutorial examples i've done. can't find q&a/docs/walkthroughs doing i'm trying do, there's chance i'm going wrong way.
i have team object many tags. team table has few normalized fields, of characteristics of team stored tags, i.e team 'virginia cavaliers' has tags
{[tag_name => 'conference', tag_value => 'acc'], [tag_name => 'division', tag_value =>'i']}
etc. db design meant accommodate many types of teams in same table, tag table facilitating search teams arbitrary criteria.
so far good. can't figure out how best access team attributes given team.
class team < activerecord::base belongs_to :sport has_many :team_subscriptions has_many :users, :through => :team_subscriptions has_many :tags def tagvalue #set hash retrieve tag value name? @tagvalue = {} tags.each |t| @tagvalue[t.tag_name] = t.tag_value end rails.logger.info(@tagvalues.keys) end end
the hash there can't access in view way i'd like.
<%= @team.tagvalue["conference"] %>
is sensible? possible? responses.
* edited based on feedback (this site awesome)*
the second suggestion slick syntacticly, has 2 hang ups can see. have catch nulls not teams have tags , show in same list:
my clumsy implementation:
has_many :tags def [](key) set = where(:tag_name => key) if set.length > 0 set.first[:tag_value] end nil end end
the clean code edgerunner:
has_many :tags def [](key) where(:tag_name => key).first.try(:tag_value) end end
and if i'm not wrong method makes database calls every time access tag. first method needs 1 when object instantiated. did both of right?
there may different way same. can define anonymous association extension , define array accessor method retrieve tags keys.
class team < activerecord::base ... has_many :tags def [](key) where(:tag_name => key).first.try(:tag_value) end end ... end
this let fetch required tags database instead of getting them @ once use 1 of them. lets this:
<%= @team.tags["conference"] %>
Comments
Post a Comment