I'm using grape-swagger gem to produce swagger documentation for dredd.
I have such params:
params do
requires :id, type: Integer, documentation: { x: { example: 1 } }
end
Grape swagger ignores example param.
Instead of this:
{
"in": "path",
"name": "id",
"type": "integer",
"format": "int32",
"required": true,
"x-example": 1
}
I got this:
{
"in": "path",
"name": "id",
"type": "integer",
"format": "int32",
"required": true
}
How to send example values for test purposes?
I found this in dredd issues. This solves my problem.
In a nutshell, the solution looks like this:
module MyApp
module AddExampleToBodyParam
module ClassMethods
private
def document_description(settings)
super
#parsed_param[:example] = settings[:example] if settings[:example]
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
end
module GrapeSwagger
module DocMethods
class ParseParams
prepend MyApp::AddExampleToBodyParam
end
end
end
Now,I can proxy example value to params body with this:
expose :some, documentation: { example: 'test' }
Related
I am working on rails 6 with ruby-2.6.5 and i am working on the API. I am using nested attributes for my order as follows:-
orders_controller.rb
# frozen_string_literal: true
module Api
module V1
class OrdersController < Api::V1::ApiApplicationController
before_action :validate_token
def create
debugger
order = OrderInteractor.create(order_params, #user_id)
if order.save
render json: { 'message' => 'Order Placed' }, status: :ok
else
render_errors(order)
end
end
private
def order_params
params.require(:data)
.require(:attributes)
.require(:order)
.permit(:user_id, :address_id, :total_price, :payment_status,
:order_number, :delivery_time_slot,
order_details_attributes:
%i[price quantity order_detail_status product_id
order_number variant_id],
payment_details_attributes:
%i[payment_data payment_id])
end
end
end
end
Api Request:-
{
"data": {
"attributes": {
"order": {
"address_id": "82",
"delivery_time_slot": "5:00 PM - 8:00 PM(Today)",
"order_details_attributes": [{
"price": "76.0",
"product_id": "46",
"quantity": "4",
"variant_id": "47"
}, {
"price": "9.9",
"product_id": "30",
"quantity": "1",
"variant_id": "29"
}],
"payment_details_attributes": [{
"payment_data": {
"data": {
"nameValuePairs": {
"razorpay_payment_id": "pay_HiHceX2p6450Wa",
"org_logo": "",
"org_name": "Razorpay Software Private Ltd",
"checkout_logo": "https://cdn.razorpay.com/logo.png",
"custom_branding": false
}
},
"paymentId": "pay_HiHceX2p6450Wa",
"userContact": "+916494949494",
"userEmail": "dailyferia#gmail.com"
}
}],
"total_price": "354"
}
},
"type": "orders"
}
}
While placing order i am getting the error Unpermitted parameter: :payment_data but it's working fine for the order_details. Please help me to fix it? I also tried the below ways to fix it but nothing worked:-
payment_details_attributes: %i[:payment_data payment_id]) and `payment_details_attributes: ['payment_data', 'payment_id'])`
Your payment_data is a complex object, rather than the scalars that are found in your order_details_attributes
You will need to add more to the permitted parameters, I believe the simplest solution would be:
payment_details_attributes: [payment_data: {}]
This should accept all parameters under payment_details_attributes, but it would also permit any other keys as well. You may want to be more strict and only allow the parameters specified above, in which case you could do:
payment_details_attributes: [
payment_data: {
data: {
nameValuePairs:
%i[razorpay_payment_id org_logo org_name checkout_logo custom_branding]
},
:paymentId, :userContact, :userEmail
}
]
which should restrict the parameters to just the format used in your example.
A few other notes:
You have %i[payment_data payment_id] in your original sample, but there is no payment_id in your payload. The attribute in the sample is paymentId, and on top of that, it is an attribute of the payment_data, not the payment_details_attributes
you wouldn't use %i and a colon, the %i is a shorthand for creating an array of ruby symbols, so %i[:payment_data payment_id] would create the array [:":payment_data", :payment_id] (note the extra colon at the beginning of payment_data)
Lastly, I haven't tested my code above, so there could be a syntax or other error, but hopefully this points you in the right direction.
I am trying to use accepts_nested_attributes_for in conjunction with a has_many association and having a lot of trouble...
Here is a simplified version of my user.rb:
class User < ActiveRecord::Base
...
has_many :user_permissions
accepts_nested_attributes_for :user_permissions
...
end
My user_permission.rb:
class UserPermission < ActiveRecord::Base
belongs_to :user
...
end
And my users_controller.rb:
class UsersController < ApiController
...
def update
#user.assign_attributes user_params
if #user.save
render partial: 'user', locals: { user: #user }
else
render json: {errors: #user.errors}.to_json, status: 500
end
end
...
private
def user_params
params.require(:user).permit(:first_name, :last_name, user_permissions_attributes: [ :user_id, :resource_id, :can_read, :can_update, :can_create, :can_delete ])
end
end
I am referencing this rails documentation on how to use accepts_nested_attributes_for with Strong Parameters.
However, when I 'puts user_params' from inside the users_controller this is all I see (no reference to the user_permissions):
{"first_name"=>"Joe", "last_name"=>"Shmoe"}
Here is an example of JSON I am submitting to the server (via angular $resource):
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": [
{
"organization_resource_id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
},
{
"organization_resource_id": 21,
"user_id": 10,
"can_create": true,
"can_read": true
}
],
}
Which returns this JSON:
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": [],
}
I am fairly confident this is an issue in my rails layer, but just for reference here is the angular User.js service I created to perform this RESTful interaction with the server:
angular.module('slics').service('User', [
'$resource', function($resource) {
return $resource('/api/users/:id', {
id: '#id'
}, {
update: {
method: 'PUT',
isArray: false
}
});
}
]);
Really not sure what I am missing here. It does not seem like it should be this difficult to submit nested attributes... but the more research I do the more I realize this does seem to be a pretty common Rails frustration.
Please feel free to comment if any additional context/information would be useful to include in my problem description to help troubleshoot this problem and I would be happy to provide it!
Strong params expects user_permissions_attributes, and you're submitting user_permissions.
Strong params is separate from accepts_nested_attributes_for (in fact, it has nothing to do with it), so however you define your require!/permit calls is exactly how your attributes should be submitted.
ProTip: To save you some future frustration, if you plan on updating through accepts nested attributes, you probably want to permit :id as well.
Well, you post an array of hashes, not a hash.
So this code
user_permissions_attributes: [ :user_id, :resource_id, :can_read, :can_update, :can_create, :can_delete ]
will permit such structure
{
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions_attributes": [
"organization_resource_id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
]
}
Try to whitelist all params at "user_permissions"
user_permissions_attributes: []
Or check out this article, to learn how to build advanced whitelists with StrongParams
http://patshaughnessy.net/2014/6/16/a-rule-of-thumb-for-strong-parameters
user_permissions_attributes: [ :user_id, :id, :can_read, :can_update, :can_create, :can_delete ]) permit :id and submitting hashes with index value..
JSON format submitting to the serve
"user": {
"id": 10,
"first_name": "Joe",
"last_name": "Shmoe",
"user_permissions": {
"0": {
"id": 20,
"user_id": 10,
"can_update": true,
"can_read": true
},
"1": {
"id": 21,
"user_id": 10,
"can_create": true,
"can_read": true
}
}
}
I've looked everywhere but nothing can help me. And I can't figure out what is the problem.
my model
class Article
include Mongoid::Document
include Mongoid::Timestamps
include Tire::Model::Search
include Tire::Model::Callbacks
mapping do
indexes :_id, :index => :not_analyzed
indexes :title
indexes :body
end
def to_indexed_json
self.to_json
end
http://localhost:9200/articles/_mapping
{
"articles": {
"article": {
"properties": {
"$oid": {
"type": "string"
},
"body": {
"type": "string"
},
"title": {
"type": "string"
}
}
}
}
}
Article.search 'love' gives no results,but there are Article with title "love", I've tried to build many requests but nothing works.
all times the same results:
"hits"=>{"total"=>0, "max_score"=>nil, "hits"=>[]}}
But If I type: Article.search "cbc267c955464f22d72a0100" it gives me article with title: "love"
So it seems to me that tire create indexes only on ID field, regardless mapping indexes on model.
When I recreate indexes
Article.index_name
=> "articles"
Tire.index('articles').delete
=> true
Article.import
my mapping becomes:
{
"articles": {
"article": {
"properties": {
"$oid": {
"type": "string"
}
}
}
}
}
UPDATED
module BSON
class ObjectId
def as_json(*args)
to_s()
end
def to_json(*args)
MultiJson.encode(as_json())
end
end
end
After implementing this initialize, all seems to work fine
I too encountered such problems while using tire. After deleting the index, you can try Article.create_elasticsearch_index and Article.tire.index.import Article.all.
The _source field in your indexed document should have title,id and body included in it, which should make it available for search.
Anyways, tire is getting retired as elasticsearch gem has now been released.
In the controller I have a respond_with like this:
respond_with(#layer1 , #layer2)
The JSON output I need is like this:
{
"LayerOne": [
{
"name": "haha",
"number":"44"
}, // more ....
],
"LayerTwo": [
{
"name": "James Bond",
"score": 20
} // , ....
]
}
So to get the first section I write the serializer like this:
class Layer1Serializer < ActiveModel::Serializer
attributes :number, :name
def name
object.person.name
end
end
And I change the controller to be like this, so I can pass a ROOT so it shows in the JSON as "LayerOne"
respond_with(#Layer1, root: 'LayerOne')
but remember at the beginning I had two things to pass to controller, so now I can't figure our how to do this for the second section of JSON that says "Layer2"
You can create the following intermediate class:
class BothLayers
include ActiveModel
def initialize(layer1,layer2)
#layer1 = layer1
#layer2 = layer2
end
attr_accessor :layer1, :layer2
end
and the following serializer:
class BothLayersSerializer < ActiveModel::Serializer
root false
has_many :layer1, key: "LayerOne"
has_many :layer2, key: "LayerTwo"
end
Then in your controller:
both_layers = BothLayers.new(#layer1,#layer2)
respond_with( both_layers, serializer: BothLayersSerializer )
Using the JBuilder DSL is an excellent way to solve your problem.
https://github.com/rails/jbuilder
The JSON response you want is implemented as a view, giving you complete control over how it renders.
create a new hash and pass your array values into it.
respond_with({:LayerOne => #layer1.as_json(:only => [:name, :percentage]), :LayerTwo => #layer2.as_json(:only => [:name, :off_target_by])})
i got this json :
{
"LayerOne": [
{
"name": "layer1",
"percentage": "10.11"
},
{
"name": "layer 1 bis",
"percentage": "1212.0"
}
],
"LayerTwo": [
{
"name": "layer 2",
"off_target_by": 2
},
{
"name": "layer 2 bis",
"off_target_by": 9
}
]
}
hope it helps :)
EDIT 2 :
You can create an array serializer to pass your variables :
class LayerArraySerializer < ActiveModel::ArraySerializer
self.root = false
end
and in your view :
respond_with({:LayerOne => #layer1 , :LayerTwo => #layer2}, :serializer => LayerArraySerializer)
json print :
[
[
"LayerOne",
[
{
"percentage": "10.11",
"name": "layer1"
},
{
"percentage": "1212.0",
"name": "layer 1 bis"
}
]
],
[
"LayerTwo",
[
{
"off_target_by": 2,
"name": "layer 2"
},
{
"off_target_by": 9,
"name": "layer 2 bis"
}
]
]
]
Railcasts has an excellent video+text tutorial on AR Serializer, I'm sure you'll find your answer there
http://railscasts.com/episodes/409-active-model-serializers
I am using Mongoid as my backend and I am in need to return json with an "id" attribute instead of the default "_id" used by mongoid
for instance, I have now
[{
"_id": "4f2d8b971773eb18e6000001",
"name": "Scooter"
}, {
"_id": "4f2d8d9f1773eb18fd000001",
"name": "Coldplay"
}]
from a call to render:
format.json { render :json => #groups, only:[:name, :_id] }
but need,
[{
"id": "4f2d8b971773eb18e6000001",
"name": "Scooter"
}, {
"id": "4f2d8d9f1773eb18fd000001",
"name": "Coldplay"
}]
Any shortcuts?
Thank you!!
If you're able to add an attribute accessor for _id called just id, then this should be easily solved by overriding as_json in your model.
def id
self._id
end
def as_json(options={})
options.merge!(:except => :_id, :methods => :id)
super(options)
end
Update: Made the override a bit more friendly to the parent method.