Hi --

On Tue, 26 Sep 2006, Giles Bowkett wrote:

>> Here's an untested version that might be improved upon but nonetheless
>> might give you some ideas:
>>
>>    %w{ inducer inhibitor substrate }.each do |thing|
>>      condition =
>>      instance_variable_set("@#{thing}s",
>>        Interaction.find(:all,
>>                         :conditions => "involvement_type = #{thing.upcase},
>>                         :include    => "drug").map {|i| i.drug.name}.uniq
>>    end
>> 
>> I've taken the liberty of changing Drug.find(interaction.drug_id).name
>> to i.drug, on the theory that if interactions have a drug_id field,
>> then they belong_to :drug, and therefore should have a drug method.
>
> change upcase to capitalize (and pull out the line condition= ) and I

Whoops -- a cut-and-paste accident :-)

[...]

> just for perspective, though, these three involvement types are the
> only possible involvement types. so merging both solutions you could
> probably do something like:
>
> Interaction.find_all.group_by(involvement_type).keys.each do |key|
> instance_variable_set( "@#{key.downcase.pluralize}",
>                                 interactions[key].map {
> |i|i.drug.name}.to_set )
> end

You can also do away with isolating the keys and then using them to
dig out the values -- just give yourself both:

Interaction.find(:all).group_by(&:involvement_type).each do |key,value|
   instance_variable_set("@#{key.downcase.pluralize}",
                                value.map {|i| i.drug.name }.to_set)
end

(I'm not sold on to_set instead of uniq, but either should be OK.)


David

-- 
                   David A. Black | dblack / wobblini.net
Author of "Ruby for Rails"   [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog)        [2] | Co-director, Ruby Central, Inc.   [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com    | [4] http://www.rubycentral.org