我有一个小型任务注册系统,用户可以在其中创建,编辑和删除他们的任务。我试图创建一个"任务已完成"单击时按钮将给定任务移动到另一页。
以下是我的控制器,查看和路线:
class TarefasController < ApplicationController
before_filter :authenticate_user!
def index
@tarefa = current_user.tarefas.all
end
def show
@tarefa = Tarefa.find(params[:id])
end
def new
@tarefa = Tarefa.new
end
def edit
@tarefa = current_user.tarefas.find_by(id: params[:id])
end
def create
@tarefa = current_user.tarefas.new(tarefa_params)
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, :time)
end
end
以下是我的观点:
<div class="row container-fluid">
<br><br><br><br>
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-info ">
<div class="panel-heading"><h3>Lista de tarefas</h3></div>
<div class="panel-body">
<button type="button" class="btn btn-default"><%= link_to 'Nova Tarefa', new_tarefa_path %></button>
<div class="table table-responsive">
<table class="table table-bordered">
<tr>
<th>Titulo</th>
<th>Descrição</th>
<th>Data e Hora</th>
<th>Cronometro</th>
<th>Estado da Tarefa</th>
<th colspan="3"></th>
</tr>
<% @tarefa.each do |tarefa| %>
<tr>
<td><%= tarefa.titulo %></td>
<td><%= tarefa.descricao %></td>
<td><%= tarefa.data %></td>
<td><%= timeago_tag tarefa.created_at, :nojs => true, :limit => 10.days.ago %></td>
<td><button type="button" class="btn btn-default"><%= link_to 'Mostrar', tarefa_path(tarefa) %></button></td>
<td><button type="button" class="btn btn-default"><%= link_to 'Editar', edit_tarefa_path(tarefa) %></button></td>
<td><button type="button" class="btn btn-default"><%= link_to 'Apagar', tarefa_path(tarefa), method: :delete, data: { confirm: 'Tem certeza?'} %></button></td>
</tr>
<% end %>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
我的路线:
Rails.application.routes.draw do
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :tarefas
match 'tarefas/tarefascompletas' => 'tarefas#completedtask', via: 'get'
root 'home#index'
end
答案 0 :(得分:1)
基本上,您可以使用update
操作创建此类按钮,而无需添加任何其他路线或操作:
<%= form_for(tarefa) do |f| %>
<%= f.hidden_field :complete, value: true %>
<%= f.submit 'Mark as complete' %>
<% end %>
如果已保留tarefa
,则会向/tarefas/:id
发送PATCH请求。
如果您真的需要不同的响应,那么标准更新会添加自定义操作。但是不要使用GET,因为GET请求应该是幂等的(不是改变资源)。相反,你想使用PATCH或PUT。
resources :tarefas do
member do
patch :complete
end
end
<%= button_to 'Mark as complete', complete_tarefa(tarefa), method: :patch %>
# PATCH /tarefas/:id/complete
def complete
@tarefa = current_user.tarefas.find_by(id: params[:id])
if @tarefa.update(complete: true)
redirect_to @tarefa
else
render 'edit'
end
end