On Sep 28, 2:49 am, Pål Bergström
<rails-mailing-l...-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:> I''ve made a survey in Rails where I want people to pick three
words,
> characteristics for different personality types, from a list of 30 words
> for 20 different visual
> details such as linear, organic, symmetry, etc.
>
> I save each answer for each user, with the visual detail in one column
> and the three words in an array in another column. E.g. for
> Linear a user doing the survey might pick Word1,Word2,Word3.
>
> What would be the best way to count Word1 picked for let''s say
> Linearity? That is counting the occurrence.
>
> One way would be:
>
> Survey.count(:conditions => "details = ''linear''
AND word like ''Word1%''")
>
> But doing that for each of the 20 visual details and for each of the 30
> words would mean a lot of queries. I suspect the answer is somehow to do
> one search and then fix it with an array or hash method.
>
I think you''d be helped more by having a database schema that matches
what you want to do better. Something like this sketch:
Detail: (id, name, position) acts_as_list, if you need the words to
come up in order
DescriptiveWord: (id, name, position) [similar to above]
SurveyResponse: (id, user_id, detail_id, descriptive_word_id)
(note that your app logic will need to constrain the user to 3 words)
All the usual associations can be set up based on this, and things
like @detail.survey_reponses.count(:group =>
''descriptive_word_id'')
[counts responses to a particular @detail and returns a hash of
word_id => count; you can get the names with some clever :join usage]
will work out of the box.
--Matt Jones