Skip to content

Commit

Permalink
Use declared to avoid mass assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
jonallured committed Mar 6, 2024
1 parent d9d67b1 commit 16581c9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
16 changes: 14 additions & 2 deletions app/api/using_grape/artworks_endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}
Expand Down
2 changes: 1 addition & 1 deletion spec/requests/using_grape/create_artwork_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 16581c9

Please sign in to comment.