I can see all the records (GET) but I can not select one (GET /: id) ... any ideas that can help me? Rails

0
class UsersController < ApplicationController

  #before_action :set_user, only: [:show, :update, :destroy]

  # GET /users
  def index
    @users = User.all
    render json: @users
    # commented out because a jbuilder template has been added
  end

  # GET /users/1
  def show
    render json: @user
    # commented out because a jbuilder template has been added
  end

  # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      render json: @user, status: :created, louserion: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /users/1
  def update
    if @user.update(user_params)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # DELETE /users/1
  def destroy
    @user.destroy
  end

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

    # Only allow a trusted parameter "white list" through.
    def user_params
      params.require(:user).permit(:username)
    end
end
    
asked by Laura 08.09.2018 в 13:55
source

1 answer

0

The action show uses the variable @user , which is created in the callback before_action ; but you have commented that line, so that @user is blank at the time of being used in show .

Simply enable the line with the callback :

class UsersController < ApplicationController

  before_action :set_user, only: [:show, :update, :destroy]

  ...
end

index works correctly because you do not need that variable, use @users , which you are creating within the same action.

    
answered by 08.09.2018 в 16:12