1

I am using Rails 5 in API mode. On querying my server for a resource, I only receive the ID, created_at, and updated_at attributes of my resource.

Everything seems fine when I query it directly from the rails console:

>> GoodThing.find 2
  GoodThing Load (0.5ms)  SELECT  "good_things".* FROM "good_things" WHERE "good_things"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
#<GoodThing:0x007fa62e4797b8> {
            :id => 2,
       :content => "hello there",
          :date => Fri, 02 Sep 2016,
       :user_id => 1,
    :created_at => Fri, 02 Sep 2016 17:30:17 UTC +00:00,
    :updated_at => Fri, 02 Sep 2016 17:30:17 UTC +00:00
}

But when I hit the endpoint localhost:3000/good_things/2.json, I get

{
  "id": 2,
  "created_at": "2016-09-02T17:30:17.335Z",
  "updated_at": "2016-09-02T17:30:17.335Z"
}

My Controller:

 class GoodThingsController < ApplicationController
  before_action :set_good_thing, only: [:show, :update, :destroy]

  # GET /good_things
  # GET /good_things.json
  def index
    @good_things = GoodThing.all
  end

  # GET /good_things/1
  # GET /good_things/1.json
  def show
    # try forcing rendering
    render json: @good_thing
  end

  # POST /good_things
  # POST /good_things.json
  def create
    @good_thing = GoodThing.new(good_thing_params)

    if @good_thing.save
      render :show, status: :created, location: @good_thing
    else
      render json: @good_thing.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /good_things/1
  # PATCH/PUT /good_things/1.json
  def update
    if @good_thing.update(good_thing_params)
      render :show, status: :ok, location: @good_thing
    else
      render json: @good_thing.errors, status: :unprocessable_entity
    end
  end

  # DELETE /good_things/1
  # DELETE /good_things/1.json
  def destroy
    @good_thing.destroy
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def good_thing_params
      params.fetch(:good_thing, {})
    end
end
4

1 回答 1

0

这对我来说适用于显示和索引方法:

def show
  render json: @good_thing.to_json
end

对于索引:

def index
 # try forcing rendering
 @good_things = GoodThing.all
 render json: @good_things.to_json
end
于 2020-01-24T03:22:31.503 回答