Tsugihagi
Tsugihagi

Reputation: 145

Rails 4 - How to populate an array through a form

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).

Upvotes: 0

Views: 87

Answers (1)

chumakoff
chumakoff

Reputation: 7024

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.

Upvotes: 2

Related Questions