Nitin Kumar
Nitin Kumar

Reputation: 184

Grape API group parameter not working

I want to create a post method in grape where i want to collect all the params once

currently I am using it like

params do
  requires :id, type: Integer, desc: "post id"
  requires :title, type: String, desc: "Title"
end
post do
  post = Post.new(:id => params[:id],:title => params[:tile])
end 

after googling I found something like

params do
  group :post do
    requires :id, type: Integer, desc: "post id"
    requires :title, type: String, desc: "Title"
  end
end

post do
  #post = Post.new(params[:post])
  #post.save
end 
but it is also asking for post hash

I also want to file upload (i.e params to add file)

Upvotes: 1

Views: 1541

Answers (1)

user473305
user473305

Reputation:

Your code will work if you declare the :post group as a Hash type (the default type is Array):

params do
  group :post, type: Hash do
    requires :id, type: Integer, desc: "post id"
    requires :title, type: String, desc: "Title"
  end
end

However, what this does is a bit different from what you're expecting: It defines a post parameter with id and title as subscripts. So the data your endpoint is expecting now looks like this:

post[id]=100&post[title]=New+article

What you're trying to do here is unnecessary anyway, though. Since params is a hash with the names of the endpoint parameters as keys, and the attributes your Post object is expecting are named identically to your endpoint parameters, you can simply do this:

params do
  requires :id, type: Integer, desc: "post id"
  requires :title, type: String, desc: "Title"
end
post do
  post = Post.new(params)
end 

Of course you should always sanitize any data you receive from the user before acting on it, so this kind of shortcut is appropriate only for personal or prototype-quality apps.

Upvotes: 3

Related Questions