rockyroadster555
rockyroadster555

Reputation: 343

Have find_by in rails return multiple results

I am trying to return all groups created by a user. All of the groups are associated with the user id. When I run a find_by query it only returns the first result. Is there a way for it to return multiple? Thanks in advance

Upvotes: 18

Views: 13145

Answers (4)

AarCee
AarCee

Reputation: 863

I'm writing a separate answer because I can't comment on James Lowrey's answer as I don't have 50 points.

find_all_by is deprecated (Ruby 4.2).

To get a list of active records from models, do:

Model.where(attribute_name: val)

For example, to find all records in Vehicle table (having column name "model_name") such that the value of model_name is "Audi", do

@vehicles = Vehicle.where(model_name: "Audi")

You can iterate through these like so:

<%  @vehicles.each do |vehicle| %>

Upvotes: 32

James L.
James L.

Reputation: 14515

I think find_all_by may be deprecated now (at least, I couldn't get it to work). I believe the 'where' function is now recommended

where("name LIKE ?","%#{search}%")
where(instructor_id: params[:choosen_instructor_id])   
where ("id = ?",id_val)

In case you didn't know, the ? and parameter list is to prevent SQL injections

Upvotes: 3

vidur punj
vidur punj

Reputation: 5871

User class has id as primary key.
which is stored as user_id in Group class
Then to find all groups associated with that user could be found as.
@groups=Group.find_all_by_user_id(user_id)

Upvotes: 0

ctide
ctide

Reputation: 5257

Change find_by to find_all_by and it will return all matching results.

Upvotes: 15

Related Questions