Rails - 用2个字段查找?

时间:2010-10-14 19:03:06

标签: ruby-on-rails ruby-on-rails-3

我在控制器中有以下内容

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

但我希望它也可以通过另一个参数找到project_id

我怎样才能在Rails中做这样的事情?

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

4 个答案:

答案 0 :(得分:65)

是的,您可以通过多种方式进行查找。

以下示例有效:

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

- 请注意,您的示例有两个user_ids

在rails 2.x中,您还可以使用条件

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

在Rails 3中,你可以很酷:

@permission = Permission.where(:user_id=>params[:user_id]).where(:project_id=>params[:project_id]).first

答案 1 :(得分:60)

Rails 4引入了find_by方法:

Permission.find_by(user_id: params[:user_id], project_id: params[:project_id])

答案 2 :(得分:4)

试试这个:

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

答案 3 :(得分:4)

Rails 3方式的范围:

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

然后您就可以使用它:

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