我的 Admin :: StylesController increase_order 和 decrease_order ,出现 RecordNotFound 错误>,但基本行动运作良好。
Ruby版本:
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
Rails版本:
Rails 4.1.4
这是我的错误:
ActiveRecord::RecordNotFound (Couldn't find Style without an ID):
app/controllers/admin/styles_controller.rb:50:in `set_style'
这是我的控制器:
class Admin::StylesController < Admin::ApplicationController
before_action :set_style, only: [:show, :edit, :update, :destroy, :increase_order, :decrease_order]
def index
@styles = Style.all
end
def new
@style = Style.new
end
def edit
end
def create
@style = Style.new(style_params)
if @style.save
redirect_to admin_styles_url, notice: 'Style was successfully created.'
else
render action: 'new'
end
end
def update
if @style.update(style_params)
redirect_to admin_styles_url, notice: 'Style was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@style.destroy
redirect_to admin_styles_url, notice: 'Style was successfully destroyed.'
end
def increase_order
@style.update_attribute(:order, @style.order += 1)
redirect_to admin_styles_url
end
def decrease_order
@style.update_attribute(:order, @style.order -= 1)
redirect_to admin_styles_url
end
private
def set_style
@style = Style.find(params[:id])
end
def style_params
params.require(:style).permit(:name, :order, :cover)
end
end
以下是我的观点:
%h3 Liste des Styles
%table.table.table-striped.table-condensed
- @styles.each do |style|
%tr
%td= style.name
%td= style.order
%td.btn-group.btn-group-xs # These two links work well.
= link_to edit_admin_style_path(style), :class => 'btn btn-primary' do
%span.glyphicon.glyphicon-pencil
= link_to [:admin, style], :method => :delete, :data => { :confirm => 'Voulez-vous supprimer ce style ?' }, :class => 'btn btn-primary' do
%span.glyphicon.glyphicon-remove
%td.btn-group.btn-group-xs # These two links return a RecordNotFound error.
= link_to admin_style_increase_order_path(style), :class => 'btn btn-primary' do
%span.glyphicon.glyphicon-arrow-up
= link_to admin_style_decrease_order_path(style), :class => 'btn btn-primary' do
%span.glyphicon.glyphicon-arrow-down
= link_to new_admin_style_path, :class => 'btn btn-primary btn-sm' do
%span.glyphicon.glyphicon-plus
Nouveau style
这是我的routes.rb:
Rails.application.routes.draw do
root 'welcome#index'
namespace :admin do
root 'dashboard#index'
resources :styles do
get 'increase_order'
get 'decrease_order'
end
end
end
提前感谢您的协助。
答案 0 :(得分:0)
您的increase_order
和decrease_order
操作应定义为资源路由的成员操作(因此您获得id
param):
resources :styles do
member do
get :increase_order
get :decrease_order
end
end
并且在视图中,要链接到这些操作:
link_to [:increase_order, :admin, style], :class => 'btn btn-primary' do
和
link_to [:decrease_order, :admin, style], :class => 'btn btn-primary' do
我还建议您可以通过post
或put
而不是get
HTTP方法访问这些操作。