I am making a simple application where the user can delete, edit, view and create tasks, the tasks have description, title and date that must be executed.
I deployed devise to register users and login users, but I have difficulty "scoping" the tasks by user, that is, the user will log in and can view, edit and delete only the tasks created by it.
My schema is:
ActiveRecord::Schema.define(version: 20170407164641) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "tarefas", force: :cascade do |t|
t.string "titulo"
t.text "descricao"
t.datetime "data"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_tarefas_on_user_id", using: :btree
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
end
end
I used belongs_to: user and has_many: tasks.
My tasks_controller:
class TarefasController < ApplicationController
before_filter :authenticate_user!
def index
@tarefa = Tarefa.all
end
def show
@tarefa = Tarefa.find(params[:id])
end
def new
@tarefa = Tarefa.new
end
def edit
@tarefa = Tarefa.find(params[:id])
end
def create
@tarefa = Tarefa.new(tarefa_params)
@user = current_user
if @tarefa.save
redirect_to @tarefa
else
render 'new'
end
end
def update
@tarefa = Tarefa.find(params[:id])
if @tarefa.update(tarefa_params)
redirect_to @tarefa
else
render 'edit'
end
end
def destroy
@tarefa = Tarefa.find(params[:id])
@tarefa.destroy
redirect_to tarefas_path
end
private
def tarefa_params
params.require(:tarefa).permit(:titulo, :descricao, :data)
end
end