1

Possible Duplicate:
NoMethodError (undefined method `[]' for nil:NilClass)

I am new to rails 3, and I am trying to render something to an HTML form:

<td class="kanban-task-handler">by: <%=h (!@tasks[activity['taskid']]['assignee'].nil? ? @tasks[activity['taskid']]['assignee'] : '') %></td>

but I'm getting this error:

undefined method `[]' for nil:NilClass):

but I'm checking this variable and stating if it's nil--> then print out nothing... so why isn't this working?

Community
  • 1
  • 1
devmonster
  • 323
  • 2
  • 12
  • Could you tell us how your data looks like? You have a Task, Activity models? What's @tasks and activity in your code sample? – Ismael Abreu Dec 23 '12 at 18:21

4 Answers4

2

I'm not sure what you're trying to do here, but it seems like @tasks is nil here. You could just check it with @tasks.nil?

But remember, if the @tasks is an array it will not give you nil? -> true instead you need to use <Array>.empty?

A safer way of checking this is:

@task.try(:attribute).try(:attribute2) etc
halfer
  • 19,824
  • 17
  • 99
  • 186
sameera207
  • 16,547
  • 19
  • 87
  • 152
1

Maybe you should model it in a different way.

Why you do @tasks[activity['taskid']]['assignee']in the first place ???

You should be able to do something like activity.assignee or `activity.task.assignee``

I guess you have a Activity, Task and Assignee model. Ok, maybe you don't have Assignee.

But with the first 2 you could do something like this, and following to the Law of Demeter you shouldn't call methods of more than one class.

class Task < ActiveRecord::Base
  has_many :activities

  def assignee_name
    try(:assignee) || 'No assignee' # or ''
  end
end

class Activity < ActiveRecord::Base
  belongs_to :task

  delegate :assignee_name, to: :task
end

Now you could this

<td class="kanban-task-handler">by: <%=h ativity.assignee_name %></td>
Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
0

I would say try:

td class="kanban-task-handler">by: <%=h (!@tasks[activity['taskid']]['assignee']) or ""%></td>

weddingcakes
  • 653
  • 1
  • 7
  • 14
0

You can also use rescue keyword to handle exception in the same line, try this

<td class="kanban-task-handler">by: <%=h (@tasks[activity['taskid']]['assignee'] rescue '') %></td>
Raghvendra Parashar
  • 3,883
  • 1
  • 23
  • 36