1

I'm working on a system that tracks illnesses and symptoms associated with them through Ruby on Rails. I have a "illnesses" table and a "symptoms" table and they have a many_to_many relationship through the "symptoms_illnesses" table. For now, I'm working on a page that displays a single entry of the "symptoms_illnesses" table. This table has two columns: illness_id and symptom_id.

I need a way to display the illness and symptom that match the ID.

Example: "illness" table has "Common Cold" under id = 1

"symptom" table has "Fever" under id = 1

"symptoms_illness" table has illness_id = 1 and symptom_id = 1.

I want the "symptoms_illness/1" page to display "Common Cold" and "Fever", but I see no obvious way to do it. Other topics in this site don't seem to address the problem in a satisfactory way.

Edit 1: I didn't add anything to the show action besides the "default"

def show
        @symptoms_illness = Symptoms_illness.find(params[:id])
end
Tsugihagi
  • 145
  • 6
  • Could you post what's in the `show` action in your `symptoms_illness` controller? – Leo Brito Sep 22 '15 at 15:07
  • Added to post, there isn't much there, just the default. The Show page just shows the ids (1 and 1) for now – Tsugihagi Sep 22 '15 at 15:11
  • `find` returns the first result of a query. To obtain all results, you should use `where`, like so: `@symptoms_illness = Symptoms_illness.where(id: params[:id])`. Check [this question](http://stackoverflow.com/questions/9574659/rails-where-vs-find) for more info about `find` and `where`. – Leo Brito Sep 22 '15 at 15:13

2 Answers2

0
def show
    @symptoms_illness = Symptoms_illness.includes(:illness,:symptom).where(id: params[:id])
end

in your view

<%= @symptoms_illness.illness.name %>
<%= @symptoms_illness.symptom.name %>

PS: not tested

Florin Ionita
  • 271
  • 1
  • 6
  • Seems to give "undefined method 'illness' for for # – Tsugihagi Sep 22 '15 at 16:21
  • can you post the models relationships – Florin Ionita Sep 22 '15 at 16:57
  • I don't think I have a version of it in English, but the relevant tables for this problem are: Illness: int id, string name, string description; Symptoms: int id, string name, string description; Symptom_illness: int id, int illness_id, int symptoms_id; Many to Many relationship between Symptoms and Illnesses linked by the "S_I" table – Tsugihagi Sep 25 '15 at 17:32
0

After doing some research I found out how to do it:
First, I created @illness and @symptom instances to the symptom_illness_controller. Then, in the show action, I added two find_by_id.
Finally, in the Show view, I changed @symptomillness.illness_id to @symptomillness.illness.name, now it shows up fine.

This may not be the cleanest way to do it but it works for what I wanted to accomplish.

Tsugihagi
  • 145
  • 6