0

I have three tables: illness, symptom and a secondary table to link the other two on a has_many through: relationship.

I wish to implement a system where users type in their symptoms and receive a list of possible illnesses.

Using the code below I can use find(1,2), for example, to show all illnesses that have symptoms 1 and 2 simultaneously. However, I want these two constants to be user-supplied data fed through a form. I'm somewhat new to RoR so I don't know how to do this.

symptoms = Symptom.find(params[:symptom_ids]) # symptom_ids is an array of ids

illnesses = Illness.joins(illness_symptoms: :symptom)
                    .where("symptoms.id in (?)", symptoms)
                    .group("illnesses.id")
                    .having("count(illnesses.id) >= ?", symptoms.length)

In the model:

 scope :with_symptoms, -> (symptoms) { joins(illness_symptoms: :symptom)
                                            .where("symptoms.id in (?)", symptoms)
                                            .group("illnesses.id")
                                            .having("count(illnesses.id) >= ?", symptoms.length) }

I use these with Illness.with_symptoms(Symptom.find(1,2)) (I'm looking for a way to replace 1,2 with user-supplied data).

2
  • I'm confused - if params[:symtom_ids] is the array of symptom ids the user has picked, doesn't your code already do what you want? Commented Nov 12, 2015 at 22:16
  • That's the thing, and I imagine it's quite a basic thing that I just didn't learn, I haven't been able to populate that array through a form. Commented Nov 12, 2015 at 22:28

1 Answer 1

2

You can do something like this in a form:

<% form_tag some_path do %>
    <% @symptoms.each do |symptom| %>
        <%= label_tag do %>
          <%= check_box_tag "symptom_ids[]", symptom.id %>
          <%= symptom.name %>
        <% end %>
    <% end %>
<% end %>

User will be able to use checkboxes to choose symptoms.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I needed, thank you so much. One question though: In the view, the check boxes look slightly above the names, as per nature of the code. Any way to fix this?
One common solution is to put the checkbox and the text into a label. It shows inline, looks good and what's very important it allows to check by clicking either on the checkbox or on the text. I edited my answer to show what I mean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.