From 16581c9a932f7d92288de88357db4862856f3173 Mon Sep 17 00:00:00 2001 From: Jon Allured Date: Tue, 5 Mar 2024 16:37:02 -0600 Subject: [PATCH] Use declared to avoid mass assignment --- app/api/using_grape/artworks_endpoint.rb | 16 ++++++++++++++-- spec/requests/using_grape/create_artwork_spec.rb | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/api/using_grape/artworks_endpoint.rb b/app/api/using_grape/artworks_endpoint.rb index afc813c..63d7fd6 100644 --- a/app/api/using_grape/artworks_endpoint.rb +++ b/app/api/using_grape/artworks_endpoint.rb @@ -11,8 +11,14 @@ class ArtworksEndpoint < Grape::API Artwork.find(params[:id]) end + params do + requires :amount_cents, type: Integer + requires :artist_name, type: String + requires :medium, type: String + requires :title, type: String + end post do - artwork = Artwork.new(params) + artwork = Artwork.new(declared(params, include_missing: false)) if artwork.save artwork else @@ -21,9 +27,15 @@ class ArtworksEndpoint < Grape::API end end + params do + optional :amount_cents, type: Integer + optional :artist_name, type: String + optional :medium, type: String + optional :title, type: String + end put ":id" do artwork = Artwork.find(params[:id]) - if artwork.update(params) + if artwork.update(declared(params, include_missing: false)) artwork else errors = {errors: artwork.errors.full_messages.to_sentence} diff --git a/spec/requests/using_grape/create_artwork_spec.rb b/spec/requests/using_grape/create_artwork_spec.rb index 2676464..e79fce0 100644 --- a/spec/requests/using_grape/create_artwork_spec.rb +++ b/spec/requests/using_grape/create_artwork_spec.rb @@ -6,7 +6,7 @@ params = {} post "/api/using_grape/artworks", params: params expect(response.status).to eq 400 - expect(response.parsed_body.key?("errors")).to eq true + expect(response.parsed_body.key?("error")).to eq true end end