Rails - Find By with 2 fields?

前端 未结 4 1199
再見小時候
再見小時候 2021-02-01 12:42

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 a

相关标签:
4条回答
  • 2021-02-01 12:48

    Try this:

    @permission = Permission.find(:conditions => ['user_id = ? and project_id = ?', params[:user_id], params[:project_id]])
    
    0 讨论(0)
  • 2021-02-01 12:57

    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
    
    0 讨论(0)
  • 2021-02-01 13:05

    Rails 4 introduces the find_by method:

    Permission.find_by(user_id: params[:user_id], project_id: params[:project_id])
    
    0 讨论(0)
  • 2021-02-01 13:05

    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])
    
    0 讨论(0)
提交回复
热议问题