Reputation: 353
Am new to rails and i have an application that allows the user to sign in and create a deadline for a project, my question is am using devise and I want to set it so when a new deadline is created i assign it to the users id. I tried the following in my new and create methods:
class DeadlinesController < ApplicationController
def new
@deadline = current_user.deadlines.new
end
def create
@deadline = current_user.deadlines.new(params[:deadline].permit(:title, :date, :description))
if @deadline.save
redirect_to @deadline
else
render 'new'
end
end
def show
@deadline = Deadline.find(params[:id])
end
def edit
@deadline = Deadline.find(params[:id])
end
def index
@deadlines = Deadline.all
@deadlines = Deadline.paginate(:page => params[:page], :per_page => 5)
end
def update
@deadline = Deadline.find(params[:id])
if @deadline.update(params[:deadline].permit(:title, :date, :description))
redirect_to @deadline
else
render 'edit'
end
end
def destroy
@deadline = Deadline.find(params[:id])
@deadline.destroy
redirect_to deadlines_path
end
private
def post_params
params.require(:deadline).permit(:title, :date, :description)
end
end
When I try @deadline = current_user.deadlines.new
I get in error as undefined method deadlines' for #<User:0x007fa37b6127d8>
?
Upvotes: 1
Views: 907
Reputation: 6464
Yes, you need to add user_id
column to deadlines table.
In the terminal, navigate to your Rails app and type:
rails generate migration add_user_id_to_deadlines user_id:integer
This will create a migration automatically that has the user_id
column in the deadlines table. You can then migrate the database again to add the latest changes:
rake db:migrate
Also modify your deadline.rb to include belongs_to :user
and user.rb to include has_many :deadlines
Upvotes: 2