我正在创建一个简单的应用程序,用户可以删除,编辑,查看和创建任务,任务包含应该执行的描述,标题和日期。
我部署了设备来注册用户和用户登录,但是我很难按用户“确定”任务,即用户将登录并且只能查看,编辑和删除他创建的任务。
我的架构:
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
我使用了belongs_to:user和has_many:tasks。
我的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
答案 0 :(得分:0)
如果您在User和Tarefa模型之间创建了一对多关系,请在用户
下创建新的Tarefa记录我认为这些任务编辑/修改选项仅在登录后可供用户使用,因此请将控制器更改为:
def edit
@tarefa = current_user.tarefas.find_by(id: params[:id])
end
def create
@tarefa = current_user.tarefas.new(tarefa_params)
@user = current_user
if @tarefa.save
redirect_to @tarefa
else
render 'new'
end
end
def update
@tarefa = current_user.tarefas.find_by(id: params[:id])
if @tarefa.update(tarefa_params)
redirect_to @tarefa
else
render 'edit'
end
end
def destroy
@tarefa = current_user.tarefas.find_by(id: params[:id])
@tarefa.destroy
redirect_to tarefas_path
end
private
def tarefa_params
params.require(:tarefa).permit(:titulo, :descricao, :data)
end
end
如果要列出与用户相关的所有tarefas,可以使用
list_of_user_tasks = current_user.tarefas
或
user = User.find_by(id: any_user_id)
list_of_user_tasks = user.tarefas
这是基本而简单的,但还有更多的方法。