Breno
Breno

Reputation: 6302

Each method in rails acts different when Model.all from Model.find_by

When I get my @variables with:

@variables = Variable.all

I can do

@variables.each do |variable|

just fine, but when I get it with the find_by, like so:

@variables = Variable.find_by_user_id(user.id)

I get an each method not found error!

Upvotes: 1

Views: 113

Answers (1)

Nick Colgan
Nick Colgan

Reputation: 5508

The find_by_field methods return a single record, which you can't iterate over.

What you want is

Variable.where(:user_id => user.id)

or

Variable.find_all_by_user_id(user.id)

or (assuming you have an association set up properly)

user.variables

Upvotes: 2

Related Questions