Search code examples
ruby-on-railsrubyruby-on-rails-4active-directorystrong-parameters

Finding a Model with Params other than ID


I'm using Rails 4 with strong parameters to try to find a user by a parameter called "provider_id". The hope is that I'll be able to make a call with my API to a URL such as:

url.com/api/v1/user?provider=facebook?provider_id=12345

My routes are as follows: routes.rb

namespace :api do
    namespace :v1 do
        resources :users
        match '/:provider/:provider_id', to: 'users#find_by_provider', via: 'get'
    end
end

My Strong parameters are:

def user_params
    params.require(:user).permit(:name, :age, :location, :provider, :provider_id) if params[:user]
end

My Function is:

def find_by_provider
    @user = User.find(params[:provider_id])

    respond_to do |format|
        format.json { render json: @user }
    end
end

Currently, I'm testing with: url.com/api/v1/facebook/12345 and it is returning:

"{"provider"=>"facebook",
"provider_id"=>"12345"}"

which is good! But I now get the error: "Couldn't find User with id=12345"

Also, somewhat related: occasionally I receive an error that says "param not found: user".

Any suggestions? Thanks!


Solution

  • Change:

    @user = User.find(params[:provider_id])
    

    To:

    @user = User.find_by(:provider_id => params[:provider_id])