Jan
Jan

Reputation: 259

Undefined Method when using current_user from Devise

I have just started using device. I set up everything according to the instructions: 1. Defined default url options in your environment files, 2.Set the routes 3. Inserted flash messages 4. Generated the views and user model.

Sign up / Sign in etc. is working fine but when using the current_user helper from devise inside my controller like this (submissions_controller.rb):

   ...
   before_filter :authenticate_user!, :except => [:index, :show]
   ...

  def new
    @submit = current_user.Submit.new
    respond_with(@submit)
  end



  def create
    @submit = current_user.Submit.new(submit_params)
    @submit.save
    respond_with(@submit)
  end

I am getting the following error:

NoMethodError in SubmitsController#new
undefined method `Submit' for #<User:0x007fea99a46f38>

Extracted source (around line #18):

  def new
    @submit = current_user.Submit.new
    respond_with(@submit)
  end

Any ideas what might cause this?

Upvotes: 0

Views: 1261

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

I don't know what's the association between User and Submit, so

if user has many submits then change current_user.Submit.new to

current_user.submits.new

else if user has one submit

current_user.build_submit

Now using the above changes in your new and create actions

def new
  @submit = current_user.submits.new
  respond_with(@submit)
end

def create
  @submit = current_user.submits.new(submit_params)
  @submit.save
  respond_with(@submit)
end

and your submit_params should look like

def submit_params 
  params.require(:submit).permit(:title, :url) 
end

require(:submit) is correct

Hope it hepls!

Upvotes: 1

Nermin
Nermin

Reputation: 6100

You have this line of code

@submit = current_user.Submit.new(submit_params)

It is failing here, because you are calling Submit method on user object, and you do not have Submit method. By looking at your code I see you wanted to create new Submit.

You should write

@submit = Submit.new(submit_params) # instantiate new Submit object

Upvotes: 0

Related Questions