Krawalla
Krawalla

Reputation: 198

display "name" insted of "_id" in index view

I've got "demand", "shift" and "parent" (this is going to be a baby sitter thingy).

Now the models look like this:

class Demand < ActiveRecord::Base
 belongs_to :parent
 belongs_to :shift
end

&

class Parent < ActiveRecord::Base
 has_many :demands, :dependent => :destroy
 has_many :shifts, :through => :demands
accepts_nested_attributes_for :demands, allow_destroy: true
# Returns fullname of parent
 def fullname
 "#{firstname} #{name}"
 end
end

&

class Shift < ActiveRecord::Base 
 has_many :supps, :dependent => :destroy 
 has_many :nanns, :through => :supps

 has_many :demands, :dependent => :destroy
 has_many :parents, :through => :demands 
end

If I now want to display a shift's description (a param of the shift table) instead of its _id, I get the following error:

undefined method `description' for nil:NilClass

Here is some code from the corresponding demands index view:

    <td><%= demand.parent.name %></td>
    <td><%= demand.demand %></td>
    <td><%= demand.shift.description %></td> <----THIS LINE PRODUCES THE ERROR
    <td><%= link_to 'Show', demand %></td>
    <td><%= link_to 'Edit', edit_demand_path(demand) %></td>
    <td><%= link_to 'Destroy', demand, method: :delete, data: { confirm: 'Are you sure?' } %></td>

I think that I gave the models the correct has_many and belongs_to associations so I don't really find the mistake here. Thanks in advance for any help!

Upvotes: 1

Views: 54

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You have a demand that has no associated shift. If you want to identify which one in your table, replace...

  <td><%= demand.shift.description %></td>

with

  <td><%= demand.shift ? demand.shift.description : 'missing shift!' %></td>

The lines with missing shifts will now tell you that shift is missing.

Upvotes: 2

Related Questions