Question

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!

Was it helpful?

Solution

Change:

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

To:

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

OTHER TIPS

find method will alyways search objects with the id column. Use the where method to search by other criterias/columns

Use:

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

Take a look at http://guides.rubyonrails.org/active_record_querying.html if you want to learn more about the active record query interface.

This is a perfect example where to use find_by! (note the !).

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

It works like find_by and returns one User. But if the user is not found it raises an ActiveRecord::RecordNotFound error. That exception is handled by Rails automatically and is turned into a 404 error page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top