Em Sta
Em Sta

Reputation: 1696

Ruby on Rails, display the name(typ in model) of category

In my projekt i have two models, an "Treatment"-Model and a "Category"-Model

class Category < ActiveRecord::Base
attr_accessible :typ
has_many :treatments
end  

class Treatment < ActiveRecord::Base
belongs_to :patient
belongs_to :category
attr_accessible :content, :day, :typ, :category_typ
end

So in my treatment form the user can also choose the category:

<div class="field">
<%= f.label :category_id %><br />
<%= f.collection_select :category_id, Category.find(:all), :id, :typ %>
</div>

My problem is that later i can display the category_id but i really dont know how i can display the catogory typ:

<% @patient.treatments.each do |treatment| %>
<tr>
<td><%= treatment.category_id %></td>
<td><%= treatment.content %></td>
<td><%= treatment.day %></td>
</tr>
<% end %>

I tried category_typ, but didnt worked! Im beginner in rails and i hope somebody can help me! Thanks!

def show
@patient = Patient.find(params[:id])

respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @patient }
end
end

Upvotes: 0

Views: 271

Answers (3)

Ermin Dedovic
Ermin Dedovic

Reputation: 907

You use treatment.category.typ.

You also need @patient = Patient.where(:id => params[:id]).includes(:treatment => [:category]).first in your controller.

Upvotes: 1

jvans
jvans

Reputation: 2915

it works with

  <td><%= treatment.category && treatment.category.typ %></td>

because category is nil for some treatment objects. If treatments need to have a category I would put a validation on the model level as well as a foreign key restrction on the database.

  class Treatment
    validates_presence_of :treatment
  end

and then in a migration

  remove_column :treatments, :category_id
  add_column :treatments, :category_id, :null => false

this will ensure referential integrity in your database. if the relationship is not required then ignore this. You can also make your code 1 method call by using .try

 <td><%= treatment.category.try(:typ)%></td>

Upvotes: 1

Em Sta
Em Sta

Reputation: 1696

Ok somehow it works with

<td><%= treatment.category && treatment.category.typ %></td>,

maybe someone knows why this works?

Upvotes: 1

Related Questions