Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Find By with 2 fields?

I have the following in a controller

def update
    @permission = Permission.find_by_user_id(params[:user_id])

But I want it to also find by another param, project_id

How can I do something like this in Rails?

@permission = Permission.find_by_user_id_and_project_id(params[:user_id],params[:user_id])
like image 971
AnApprentice Avatar asked Oct 14 '10 19:10

AnApprentice


2 Answers

Rails 4 introduces the find_by method:

Permission.find_by(user_id: params[:user_id], project_id: params[:project_id])
like image 78
Fred Willmore Avatar answered Nov 13 '22 04:11

Fred Willmore


Yes, you can do finds in a bunch of ways.

Your example below works:

@permission = Permission.find_by_user_id_and_project_id(params[:user_id],params[:project_id])

-- Note your example had two user_ids

In rails 2.x you can also use conditions

@permission = Permission.find(:conditions=>["user_id=? and project_id=?", params[:user_id], params[:project_id]])

And in Rails 3, you can be cool like:

@permission = Permission.where(:user_id=>params[:user_id]).where(:project_id=>params[:project_id]).first
like image 67
Jesse Wolgamott Avatar answered Nov 13 '22 04:11

Jesse Wolgamott