views:

45

answers:

4

Hello,

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])

Thanks

+2  A: 

Yes, it is possible.

Eimantas
useless answer.
DGM
useless comment. The answer is in the question itself.
Eimantas
+2  A: 

Try this:

@permission = Permission.find(:conditions => ['user_id = ? and project_id = ?', params[:user_id], params[:project_id]])
Jacob Relkin
+3  A: 

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
Jesse Wolgamott
Thanks, I like the first one though... A lot cleaner.
AnApprentice
the last one is the rails 3 way... unless put into a scope.
DGM
Agree with DGM here, scopes are great.... Permission.for(@user).for(@project).first is a good for code readability
Jesse Wolgamott
+2  A: 

Rails 3 way with scopes:

scope :by_user_id_and_project_id, lambda {|user_id,project_id| 
    where(:user_id=>user_id).where(:project_id=>project_id])
}

And then you can use it like:

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