Pregunta

I had wanted to create the equivalent of scaffold for my user model which is handled by devise and since I was not allowed to create the User scaffold I created an Execs controller that will just handle the user models 7 actions.

I have no references to an exec Model but on my show and edit views I keep getting this error Couldn't find Exec with id=2 I thought it might be something rails is doing under the hood with resources :execs so I changed it to:

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

but even with that I still get the same error. Here is my 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

Here are the links from the view I am clicking:

<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> 
¿Fue útil?

Solución

The load_and_authorize_resource is trying to load a model of Exec on all instances. It sounds like the ExecsController deals with objects that are User not Exec. If this is the case, you could either a) change load_and_authorize_resource to look up User objects or b) exclude show and edit from the actions that load_and_authorize_resource will run on.

For a, change the load_and_authorize_resource line to:

load_and_authorize_resource :class_name => 'User'

and for b, change the load_and_authorize_resource line to:

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

I think you want option "a" above. If you do "a", this will allow you to get rid of the @user = User.find(...) and @user = User.new(...) lines in other controller actions, as the resource will either be found or initialized by load_and_authorize_resource.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top