How to custom status embed json in rails? - ruby-on-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

Related

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"
}
}

active model serializers rails json doesnt work inside another json object

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
},]

Generating JSON with Rails?

I just need to generate a JSON string that looks something like:
def self.feedback_request(history_event)
#event = history_event.event
#case_tracking_id = history_event.case_tracking_id
#request_type = "feedback"
return "{
"event":#event
"case_tracking_id":#case_tracking_id
"request_type":#request_type
"event_data":historic_event.to_json
}"
end
Does rails have some way to generate JSON strings?
The right way to do it is using the jbuilder which is part of Rails.
so from the documentation:
# app/views/message/show.json.jbuilder
json.content format_content(#message.content)
json.(#message, :created_at, :updated_at)
json.author do
json.name #message.creator.name.familiar
json.email_address #message.creator.email_address_with_name
json.url url_for(#message.creator, format: :json)
end
if current_user.admin?
json.visitors calculate_visitors(#message)
end
json.comments #message.comments, :content, :created_at
json.attachments #message.attachments do |attachment|
json.filename attachment.filename
json.url url_for(attachment)
end
This will build the following structure:
{
"content": "<p>This is <i>serious</i> monkey business</p>",
"created_at": "2011-10-29T20:45:28-05:00",
"updated_at": "2011-10-29T20:45:28-05:00",
"author": {
"name": "David H.",
"email_address": "'David Heinemeier Hansson' <david#heinemeierhansson.com>",
"url": "http://example.com/users/1-david.json"
},
"visitors": 15,
"comments": [
{ "content": "Hello everyone!", "created_at": "2011-10-29T20:45:28-05:00" },
{ "content": "To you my good sir!", "created_at": "2011-10-29T20:47:28-05:00" }
],
"attachments": [
{ "filename": "forecast.xls", "url": "http://example.com/downloads/forecast.xls" },
{ "filename": "presentation.pdf", "url": "http://example.com/downloads/presentation.pdf" }
]
}
So in you case your code should be something like:
json.(#event, #case_tracking_id, #request_type, historic_event)

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"
}
]

ActiveRecord Json Should fail no?

I am using the ActiveRecord Json Validator Gem and I have the following object thats trying to be saved to the model, which should fail, but instead isnt:
[1] pry(#<Api::Internal::V1::UsersController>)> backup
=> #<UserBackup:0x24eddeed
id: nil,
location_name: "test",
user_params: {"user"=>{"user_name"=>"GeorgeLucas", "email"=>"asdsadasdas", "auth_token"=>"jesus"}, "controller"=>"api/internal/v1/users", "action"=>"create"}>
[2] pry(#<Api::Internal::V1::UsersController>)> backup.save!
=> true
As you can see theres a unsaved UserBackup model object in [1] and in [2] is saves, the json in [1] is missing somethig that is set to required: first_name.
The model looks like such:
class UserBackup < ActiveRecord::Base
PROFILE_JSON_SCHEMA = Rails.root.join('config', 'schemas', 'user.json_schema').to_s
validates :location_name, :presence => true
validates :user_params, :presence => true, json: {schema: PROFILE_JSON_SCHEMA}
end
The Json Schema Looks like:
{
"type": "object",
"$schema": "http://json-schema.org/draft-03/schema",
"properties": {
"user": {
"first_name": {
"type": "string",
"required": true
},
"last_name": {
"type": "string",
"required": false
},
"user_name": {
"type": "string",
"required": true
},
"email": {
"type": "string",
"required": true,
"format": "email"
},
"auth_token": {
"type": "string",
"required": true
}
}
}
}
According to my schema, first_name must be a string and it is a required field.
In my json being saved, its missing entirely. Which means that the model should not save the object to the database.
Update One:
Looking at the model object the user_params doesn't look like a json object at all, it looks like a hash of hashes. So with that in mind, here is the controller:
module Api
module Internal
module V1
class UsersController < BaseController
before_action :restrict_api_access
def create
params_json = params.to_json
backup = UserBackup.new(location_name: from_site, user_params: params_json)
binding.pry
if backup.save
return render json: {}, status: 200
else
return render json: {}, status: 422
end
end
end
end
end
end
params_json is indeed a json object:
[3] pry(#<Api::Internal::V1::UsersController>)> params_json
=> "{\"user\":{\"user_name\":\"GeorgeLucas\",\"email\":\"asdsadasdas\",\"auth_token\":\"jesus\"},\"controller\":\"api/internal/v1/users\",\"action\":\"create\"}"
So I am unsure at this point, what exactly is going on.

Resources