Association Error with Sorcery Gem in Rails

57 views Asked by At

I used Sorcery to set up authentication in Rails and I'm trying to create a model where the user id for the user is linked as reference to the model for data entered, but I get an error:

Couldn't find User without an ID

it refers to the following code:

def create
  @user = User.find(params[:user_id])
  @certificate = @user.certificates.create(certificate_params)
  redirect_to certificate_path(@certificate)
end

To answer basic questions I've asked myself, the user is logged in...

1

There are 1 answers

0
smathy On BEST ANSWER

That's actually a very weird error if the above is really your code. You should have gotten something like Couldn't find Bar with 'id'= instead. The error above is usually only given if you provide no args to find at all, ie. User.find()

Anyway, the underlying problem here is that params[:user_id] doesn't contain the value you expect it to, and probably it contains no value at all. You haven't shown enough of your other code to determine why that is, BUT it doesn't matter...

Unless you want people to be able to just change the URL and add a certificate for some other user in your system then you shouldn't rely on the params[:user_id] for creating associated objects, you should use current_user - that's kind of the whole point of authentication.

So:

def create
  @certificate = current_user.certificates.create(certificate_params)
  redirect_to certificate_path(@certificate)
end