Rails寻找错误的模型

时间:2013-12-05 15:11:41

标签: ruby-on-rails ruby devise ruby-on-rails-4 ruby-2.0

我原本想为我的用户模型创建一个等效的脚手架,由设计人员处理,因为我不允许创建用户脚手架,所以创建了一个只处理用户模型7动作的Execs控制器。

我没有引用exec模型但是在我的节目和编辑视图中我一直收到此错误Couldn't find Exec with id=2我认为这可能是rails在resources :execs引导下的事情所以我改了它到:

get "execs/index"
get "execs/new"
get "execs/edit"
post "execs/create"
get "execs/show"
post "execs/update"
delete "execs/destroy"

但即便如此,我仍然会得到同样的错误。这是我的execs_controller.rb

class ExecsController < ApplicationController
  before_action :set_user, only: [:show, :edit, :destroy]
  before_filter :authenticate_user!
  load_and_authorize_resource

  def index
    @users = User.where("client_id = ?", current_user.client_id)
  end

  def show
  end

  def new
    @user = User.new
  end


  def edit
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to action: 'index'
    else
      render 'new'
    end
  end

  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
      redirect_to action: 'index'
    else
      render 'edit'
    end
  end

  def destroy
    @user.destroy
    redirect_to action: 'index'
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_user
    @user = User.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :phone, :position, :client_id, :password, :password_confirmation, :role_id)
  end
end

以下是我点击的视图中的链接:

<td><%= link_to 'Show', execs_show_path(id: user.id) %></td>
<td><%= link_to 'Edit', execs_edit_path(id: user.id) %></td>
<td><%= link_to 'Delete', execs_destroy_path(id: user.id) , data: { confirm: 'Are you sure?' } %></td> 

1 个答案:

答案 0 :(得分:1)

load_and_authorize_resource正在尝试在所有实例上加载Exec的模型。听起来ExecsController处理User而不是Exec的对象。如果是这种情况,您可以a)更改load_and_authorize_resource以查找User个对象,或b)从show的操作中排除editload_and_authorize_resource将继续运行。

对于a,将load_and_authorize_resource行更改为:

load_and_authorize_resource :class_name => 'User'

并且对于b,将load_and_authorize_resource行更改为:

load_and_authorize_resource :except => [:show, :edit]

你想要上面的选项“a”。如果你执行“a”,这将允许你摆脱其他控制器操作中的@user = User.find(...)@user = User.new(...)行,因为资源将由load_and_authorize_resource找到或初始化。< / p>