【问题标题】:Rails looking for wrong modelRails 寻找错误的模型
【发布时间】:2013-12-05 15:11:41
【问题描述】:

我想为我的用户模型创建等效的脚手架,由 devise 处理,由于我不允许创建用户脚手架,我创建了一个 Execs 控制器,它将只处理用户模型的 7 个动作。

我没有引用 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> 

【问题讨论】:

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


    【解决方案1】:

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

    对于 a,将 load_and_authorize_resource 行更改为:

    load_and_authorize_resource :class_name =&gt; 'User'

    对于 b,将 load_and_authorize_resource 行更改为:

    load_and_authorize_resource :except =&gt; [:show, :edit]

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2010-11-24
      • 1970-01-01
      相关资源
      最近更新 更多