No attachment path in json, join table - ruby-on-rails

Need some help..
I have user, offer and country model. The user has_one_attached :image.
Offer & User => has_and_belongs_to_many
Displaying all users grouped by country in controller:
offer = Offer.find(params[:id])
render json: offer.users.joins(:country).group_by { |t| t.country.name }
Serializer
class OfferSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :name, :image
def image
rails_blob_path(object.image, only_path: true) if object.image.attached?
end
I do get:
{"country1": [
{
"id": 9,
"country_id": 1,
"online": true,
...
{
"id": 12,
"bundesland_id": 1,
"online": true,
...
and i need to get additional:
"header_image": "/rails/active_storag...
But I don't get the user.blob path in the json!
Any idea?
Thanks for support!

Related

I want whole model return I have 2 models by using pg search in rails

I want this form
"data": [
{
"id": 2,
"searchable_type": "User",
"email": "abc",
"first_name": "abc",
"last_name": "xyz",
"created_at": "2022-08-05T09:40:18.986Z",
"updated_at": "2022-08-05T09:40:18.986Z"
},
{
"id": 3,
"searchable_type": "blog",
"tittle": "user",
"created_at": "2022-08-05T09:40:18.986Z",
"updated_at": "2022-08-05T09:40:18.986Z"
}
]
I want to return whole object for each model respectively by using Pg Search multi search it just return a content ,searchable_type and searchable_id as attached images belowIt is my postman image for blog returnIt is my postman image for user return
[My search controller, User and blog models]
class Api::V1::SearchController < Api::V1::ApiController
def index
#query = params[:value]
#results = PgSearch.multisearch(#query)
render json: { data: #results}, status: :ok
end
end
class Blog < ApplicationRecord
include PgSearch::Model
multisearchable against: [:id, :title, :created_at, :updated_at ]
end
class User < ApplicationRecord
include PgSearch::Model
multisearchable against: [:id, :email, :first_name, :last_name ]
end
Change
#results = PgSearch.multisearch(#query)
to
#results = PgSearch.multisearch(#query).includes(:searchable).map(&:searchable)

How to save a nested many-to-many relationship in API-only Rails?

In my Rails (api only) learning project, I have 2 models, Group and Artist, that have a many-to-many relationship with a joining model, Role, that has additional information about the relationship. I have been able to save m2m relationships before by saving the joining model by itself, but here I am trying to save the relationship as a nested relationship. I'm using the jsonapi-serializer gem, but not married to it nor am I tied to the JSON api spec. Getting this to work is more important than following best practice.
With this setup, I'm getting a 500 error when trying to save with the following errors:
Unpermitted parameters: :artists, :albums and ActiveModel::UnknownAttributeError (unknown attribute 'relationships' for Group.)
I'm suspecting that my problem lies in the strong param and/or the json payload.
Models
class Group < ApplicationRecord
has_many :roles
has_many :artists, through: :roles
accepts_nested_attributes_for :artists, :roles
end
class Artist < ApplicationRecord
has_many :groups, through: :roles
end
class Role < ApplicationRecord
belongs_to :artist
belongs_to :group
end
Controller#create
def create
group = Group.new(group_params)
if group.save
render json: GroupSerializer.new(group).serializable_hash
else
render json: { error: group.errors.messages }, status: 422
end
end
Controller#group_params
def group_params
params.require(:data)
.permit(attributes: [:name, :notes],
relationships: [:artists])
end
Serializers
class GroupSerializer
include JSONAPI::Serializer
attributes :name, :notes
has_many :artists
has_many :roles
end
class ArtistSerializer
include JSONAPI::Serializer
attributes :first_name, :last_name, :notes
end
class RoleSerializer
include JSONAPI::Serializer
attributes :artist_id, :group_id, :instruments
end
Example JSON payload
{
"data": {
"attributes": {
"name": "Pink Floyd",
"notes": "",
},
"relationships": {
"artists": [{ type: "artist", "id": 3445 }, { type: "artist", "id": 3447 }]
}
}
Additional Info
It might help to know that I was able to save another model with the following combination of json and strong params.
# Example JSON
"data": {
"attributes": {
"title": "Wish You Were Here",
"release_date": "1975-09-15",
"release_date_accuracy": 1
"notes": "",
"group_id": 3455
}
}
# in albums_controller.rb
def album_params
params.require(:data).require(:attributes)
.permit(:title, :group_id, :release_date, :release_date_accuracy, :notes)
end
From looking at https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html I think the data format that Rails is normally going to expect will look something like:
{
"group": {
"name": "Pink Floyd",
"notes": "",
"roles_attributes": [
{ "artist_id": 3445 },
{ "artist_id": 3447 }
]
}
}
with a permit statement that looks something like (note the . before permit has moved):
params.require(:group).
permit(:name, :notes, roles_attributes: [:artist_id])
I think you have a few options here:
Change the data format coming into the action.
Craft a permit statement that works with your current data (not sure how tricky that is), you can test your current version in the console with:
params = ActionController::Parameters.new({
"data": {
"attributes": {
"name": "Pink Floyd",
"notes": "",
},
"relationships": {
"artists": [{ type: "artist", "id": 3445 }, { type: "artist", "id": 3447 }]
}
}
})
group_params = params.require(:data).
permit(attributes: [:name, :notes],
relationships: [:artists])
group_params.to_h.inspect
and then restructure the data to a form the model will accept; or
Restructure the data before you try to permit it e.g. something like:
def group_params
params_hash = params.to_unsafe_h
new_params_hash = {
"group": params_hash["data"]["attributes"].merge({
"roles_attributes": params_hash["data"]["relationships"]["artists"].
map { |a| { "artist_id": a["id"] } }
})
}
new_params = ActionController::Parameters.new(new_params_hash)
new_params.require(:group).
permit(:name, :notes, roles_attributes: [:artist_id])
end
But ... I'm sort of hopeful that I'm totally wrong and someone else will come along with a better solution to this stuff.

How to include a nested resource that has a polymorphic association with ActiveRecordSerializer?

I'm using Netflix's jsonapi-rails gem to serialize my API. I need to build a response.json object that includes the associated comments for a post.
Post model:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
Polymorphic Comment model
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
PostSerializer
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body
has_many :comments, serializer: CommentSerializer, polymorphic: true
end
CommentSerializer
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :id, :created_at
belongs_to :post
end
Posts#index
class PostsController < ApplicationController
def index
#posts = Post.all
hash = PostSerializer.new(#posts).serialized_json
render json: hash
end
end
What I've got so far only gives me the comment type and id, but I NEED the comment's body as well.
Please help!
Thanks in advance~!
Although not very intuitive this behaviour is there by design. According to the JSON API relationship data and actual related resource data belong in different objects of the structure
You can read more here:
Fetching Relationships
Inclusion of Related Resources
To include the body of the Comments your serializers would have to be:
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
has_many :comments
end
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
end
and your controller code:
class HomeController < ApplicationController
def index
#posts = Post.all
options = {include: [:comments]}
hash = PostSerializer.new(#posts, options).serialized_json
render json: hash
end
end
The response for a single Post would look something like this:
{
"data": [
{
"attributes": {
"body": "A test post!"
},
"id": "1",
"relationships": {
"comments": {
"data": [
{
"id": "1",
"type": "comment"
},
{
"id": "2",
"type": "comment"
}
]
}
},
"type": "post"
}
],
"included": [
{
"attributes": {
"body": "This is a comment 1 body!",
"created_at": "2018-05-06 22:41:53 UTC"
},
"id": "1",
"type": "comment"
},
{
"attributes": {
"body": "This is a comment 2 body!",
"created_at": "2018-05-06 22:41:59 UTC"
},
"id": "2",
"type": "comment"
}
]
}

ActiveModel::Serializers JSON API nested associations include?

I haven't found the exactly same question on Stackoverflow. Besides AMS changes so rapidly, that even 2-year-old answers get outdated often.
I use Rails 5 API-only and the gem 'active_model_serializers' (AMS) (ver. 0.10.6).
I also use the JSONAPI response format - not simply JSON.
I need to render a nested include - not just nested relations as of now.
Code example:
serializer1:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
belongs_to :user
end
serializer2:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :cities
end
serializer3:
class CitySerializer < ActiveModel::Serializer
attributes :id, :name
end
controller:
def index
#questions = Question.all
render json: #questions, include: [:user, 'user.city']
end
I get this response:
{
"data": [
{
"id": "1",
"type": "questions",
"attributes": {
"title": "First",
"created-at": "2017-03-27T13:22:15.548Z",
"updated-at": "2017-03-27T13:22:16.463Z"
},
"relationships": {
"user": {
"data": {
"id": "3",
"type": "users"
}
}
}
}
],
"included": [
{
"id": "3",
"type": "users",
"attributes": {
"email": "client2#example.com"
},
"relationships": {
"cities": {
"data": [
{
"id": "75",
"type": "cities"
}
]
}
}
}
]
}
I really do get a nested relation city. I even get the city id.
But the problem is - how do I get other city attributes like name? I need another include section - maybe inside current include section (nested?).
How to do that? (without any additional gems)
I found some solution. I don't know about how clean is it. It is based on 2 prerequisites:
https://github.com/rails-api/active_model_serializers/blob/db6083af2fb9932f9e8591e1d964f1787aacdb37/docs/general/adapters.md#included
ActiveModel Serializers: has_many with condition at run-time?
I applied the conditional relations and user-all-permissive include:
controller:
#questions = Question.all
render json: #questions,
show_user: (param? params[:user]),
show_cities: (param? params[:city]),
include: [:user, "user.**"]
serializer1:
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :title, :created_at, :updated_at
belongs_to :user, if: -> { should_render_user }
def should_render_user
#instance_options[:show_user]
end
end
serializer2:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email
has_many :cities, if: -> { should_render_cities }
def should_render_cities
#instance_options[:show_cities]
end
end
serializer3:
class CitySerializer < ActiveModel::Serializer
attributes :id, :name
end
helper:
def param? param
param && param != "false" && param != "nil"
end
Conditional relations allow to control which include's actually to render.
The following should do it
render json: #questions, include: [:categories, user: :city]
You should also include the user in the parameter 'fields' and using strings instead of symbols for the parameter include
render json: #questions, fields: [:title, :user], include: ['user', 'user.cities']

Rails 4 AMS with three nested models

I am using active_model_serializers gem for the first time. Version which I'm using is 0.10.2
I have three models with associations like this:
class Song < ActiveRecord::Base
has_many :questions
end
class Question< ActiveRecord::Base
belongs_to :song
has_many :answers
end
class Answer< ActiveRecord::Base
belongs_to :question
end
I've generated three serializers like this:
class SongSerializer < ActiveModel::Serializer
attributes :id, :audio, :image
has_many :questions
end
class QuestionSerializer < ActiveModel::Serializer
attributes :id, :text
belongs_to :song
has_many :answers
end
class AnswerSerializer < ActiveModel::Serializer
attributes :id, :text
belongs_to :question
end
but unfortunately my json response doesn't show me the question's answers, but songs and questions are showing.
after some googling I tried to add
ActiveModelSerializers.config.default_includes = '**'
or from documentation like this:
class Api::SongsController < ApplicationController
def index
songs = Song.all
render json: songs, include: '**' #or with '*'
end
end
but this led me to stack level too deep error
So what should I do in order to get json response to looks like this -
{
"id": "1",
"audio": "...",
"image": "...",
"questions": [
{
"id": "1",
"text": ".....",
"answers": [
{
"id": "1",
"text": "...."
},
{
"id": "2",
"text": "..."
}
]
},
{
"id": "2",
"text": "....."
}
]
}
because simply adding associations like I would do in models are not helping for the third association.
Any help would be appreciated!
So finally after some more searching I found solution which worked. I had to add to my controller include with nested models.
class Api::SongsController < ApplicationController
def index
songs = Song.all
render json: songs, include: ['questions', 'questions.answers']
end
end
And it worked like a charm!
You can do it in your controller with the following structure
respond_with Song.all.as_json(
only: [ :id, :audio, :image ],
include: [
{
questions: {
only: [:id, :text],
include: {
anwers: {
only: [ :id, :text ]
}
}
}
}
]
)

Resources