active model serializers rails json doesnt work inside another json object - ruby-on-rails

iam using active model serializers in my rails, this is my snippet
# GET /users
def index
#users = User.all
render json: {data: #users, status: httpstatus[:getSuccess]}
# render json: {data: #users, status: httpstatus[:getSuccess]}
end
but its showing like this in postman
"data": [
{
"id": 38,
"name": "tyasa",
"age": 21,
"created_at": "2017-05-30T06:23:03.504Z",
"updated_at": "2017-05-30T06:23:03.504Z"
},
{
"id": 39,
"name": "wahyu",
"age": 21,
"created_at": "2017-05-30T06:23:37.359Z",
"updated_at": "2017-05-30T06:23:37.359Z"
},]
but its work when just render the #users
# GET /users
def index
#users = User.all
render json: {data: #users, status: httpstatus[:getSuccess]}
# render json: #users
end
i just wanna delete created at and update at from the json.
How to solve this..
sory bad english

I just wanna delete created at and update at from the json.
You can use except option of as_json
render json: {data: #users.as_json(:except => [:created_at, :updated_at]), status: httpstatus[:getSuccess]}
which should give you
"data": [
{
"id": 38,
"name": "tyasa",
"age": 21
},
{
"id": 39,
"name": "wahyu",
"age": 21
},]

Related

Archive .json import on rails api

I'm having problems importing a .json file and saving the data inside it in the api database. My code is like this:
def create
content = JSON.parse(File.open(params[:products]).read)
#product = Product.new(content)
if #product.save
render json: { message: 'Produto Salvo', data: #product }, status: 200
else
render json: #product.errors, status: :unprocessable_entity
end
end
The file(products.json)contains this data:
[{
"title": "Brown eggs",
"type": "dairy",
"description": "Raw organic brown eggs in a basket",
"filename": "0.jpg",
"height": 600,
"width": 400,
"price": 28.1,
"rating": 4
}, {
"title": "Sweet fresh stawberry",
"type": "fruit",
"description": "Sweet fresh stawberry on the wooden table",
"filename": "1.jpg",
"height": 450,
"width": 299,
"price": 29.45,
"rating": 4
}]
By the time I implement the method, all fields are saved as NIL:
#<ActiveRecord::Relation [#<Product id: 3, title: nil, product_type: nil, description: nil, filename: nil, height: nil, width: nil, price: nil, rating: nil, created_at: "2021-11-10 14:15:11.261454000 +0000", updated_at: "2021-11-10 14:15:11.261454000 +0000">]>
How do I save with the data correctly filled in?
It looks like you're reading in an array of multiple products?
I would suggest inserting a binding.pry between where you set content and where you set #product
Paste the value of content here and I think the solution will become clear.

Active Model Serializer not rendering the root key for collection - Version- 0.10.6

I am using 'active_model_serializers', '~> 0.10.6' for rendering my API response. For my index action I am doing this -
render json: #items, root: 'data', each_serializer: ItemsSerializer
but in my response, I am not getting the root key - data
[
{
"id": 85,
"title": "B",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
},
{
"id": 87,
"title": "D",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
}
]
What I am doing wrong here?
The hardest part with AMS is finding it's right documentation. Based on the version you have mentioned, here's the documentation link:
https://github.com/rails-api/active_model_serializers/tree/0-10-stable/docs
There are 3 adapters:
:default (There won't be any root, basically root key is useless, even if you add it)
:json (This is what you need, you can add custom root key. https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-1)
:json_api (Default root key will be data, but you can customize, maybe you can use this, but it will change the whole structure of your response json into something like: https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-2)
Answer:
render json: #items, root: 'data', adapter: :json, each_serializer: ItemsSerializer
or
render json: #items, adapter: :json, each_serializer: ItemsSerializer

How to custom status embed json in rails?

Here it's my products.controller
def index
if params[:page]
#product = Product.page(params[:page]).per(5)
else
#product = Product.order('updated_at DESC')
end
render json: {
status: '200',
message: 'OK',
data: ActiveModel::Serializer::CollectionSerializer.new(#product, each_serializer: ProductSerializer)},status: 200
end
def show
render json: {
status: '200',
message: 'OK',
data: ActiveModel::Serializer::CollectionSerializer.new(#product, each_serializer: ProductSerializer)},status: 200
end
Here my product serializer
class ProductSerializer < AplicationSerializer
attributes :id, :product_name, :category, :company, :description, :logo_img, :web_link
belongs_to :category
has_many :images
en
d
If I try to access localhost:3000/products/, it can display all the data that I want, but if I want to try localhost:3000/products/1, it's wrong, so what the wrong about my code?
{
"status": "200",
"message": "OK",
"data": [
{
"id": 1,
"product_name": "MDS",
"category": {
"id": 4,
"category": "Market Place",
"created_at": "2018-04-12T02:58:59.949Z",
"updated_at": "2018-04-12T02:58:59.949Z"
},
"company": "PT Media Data ",
"description": "ISP di Indo",
"logo_img": "mds.jpg",
"web_link": "https://mds.co/",",
"images": [
{
"id": 1,
"link": "http:/mds.com/mds.png"
},
{
"id": 2,
"link": "http:/mds.com/mds.png"
},
{
"id": 3,
"link": "http:/mds.com/mds.png"
},
{
"id": 4,
"link": "http:/mds.com/mds.png"
}
]
}
]
}
in the above is the display I want to display at http://localhost:3000/products/1, but i still got no appear, even though i can display it with same code on def index
Thanks for your help
The only thing that can seem to be missing here is setting the #product
If you have a before_action :show, :set_product this might not be the problem.
The other difference is between an array in the index and a single element in the show. you better use ProductSerializer.new(#product).as_json instead of using the collection serializer

Rails pass extra data from controller action to serializer

I need to pass extra data from the show action in the controller to the serializer on rendere method.
I have a render like this:
render json: test, serializer: TestSerializer
The json that is returned is something like this:
{
"test": {
"id": 1,
"name": "Name",
"surname": "Surname",
}
}
I need to pass extra data to this serializer in order to have a json like this:
render json: test, serializer: TestSerializer, extradata: extradata
{
"test": {
"id": 1,
"name": "Name",
"surname": "Surname",
"extradata": {
"first": 1,
"second": 12
}
}
}
Can anyone help me?
Thanks in advance.
I have done this to resolve my problem very quickly:
Controller.rb before
render json: test, serializer: TestSerializer
Json before
{
"test": {
"id": 1,
"name": "Name",
"surname": "Surname",
}
}
Controller.rb after
extradata = "test text"
render json: test, serializer: TestSerializer, extradata: extradata
Json after
{
"test": {
"id": 1,
"name": "Name",
"surname": "Surname",
"extradata": "test text"
}
}

AssociationTypeMismatch (User(#301360) expected, got Hash(#88300)) in Rails

I try to create an Object from nested json. But I get a AssociationTypeMismatch error.
I am new to ruby on rails and not sure, it is the right way to do this.
I am thankful for any tips.
The error appears in this line "#avatar.from_json(json)" in the avatars_controller.rb
Avatar.rb
class Avatar < ActiveRecord::Base
has_one :user
accepts_nested_attributes_for :user
end
User.rb
class User < ActiveRecord::Base
belongs_to :avatar
end
json
[
{
"id": 7,
"user": {
"id": 47,
"gender": "male",
"name": "Mark",
"created_at": "2015-01-07T11:44:50.991Z",
"updated_at": "2015-01-28T14:39:03.900Z"
},
"login_counter": 5,
"created_at": "2015-01-28T14:39:03.896Z",
"updated_at": "2015-03-03T12:11:43.432Z"
}
]
avatars_controller.rb
def get_data_button
json= open("http..." ).read
#avatar = Avatar.new
#avatar.from_json(json)
respond_to do |format|
if #avatar.save
format.html { redirect_to user_url }
else
format.html { render :new }
end
end
end
def avatar_params
params.require(:avatar).permit( :login_counter, user: [:gender, :name])
end
Please try like this code.
params.require(:avatar).permit( :login_counter, user_attributes: [:gender, :name])
[
{
"id": 7,
"user_attributes": {
"id": 47,
"gender": "male",
"name": "Mark",
"created_at": "2015-01-07T11:44:50.991Z",
"updated_at": "2015-01-28T14:39:03.900Z"
},
"login_counter": 5,
"created_at": "2015-01-28T14:39:03.896Z",
"updated_at": "2015-03-03T12:11:43.432Z"
}
]

Resources