T
T
The Whiz2013-07-23 20:09:47
Ruby on Rails
The Whiz, 2013-07-23 20:09:47

Understanding Variables in Rails?

Stumbled upon a problem while trying to put objects with certain qualities into variables
tasks_controller.rb:
(Rails 4)

def index
@incomplete_tasks = Task.find_by(status: 0)
@completed_tasks = Task.find_by(status: 1)
end

index.html.erb:
<% @incomplete_tasks.each do |task| %>
...
<% end %>

Throws an error undefined method `each' for #<Task:0x007fbf850f0db0>
With the banal @tasks = Task.all everything works as it should
. What's the catch?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
phil_tsarik, 2013-07-23
@modernstyle

find_byreturns a single record either nil
Try, for example, Task.where(status: 0)

I
Ivan Kryak, 2013-07-24
@sck_v

And use named scopes.
scope :completed, -> { where(status: 1) }
scope :incompleted, -> { where(status: 0) }
And access them: Task.completed, Task.incompleted

I
int03e, 2013-07-23
@int03e

find_by returns one entry, each does not. You need to do this:

@incomplete_tasks = Task.where(status: 0)
@completed_tasks = Task.where(status: 1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question