I'm using active-model-serializers for my API.
I have a model (Task) that has many subtasks(always Task model), called children.
I do this recursive has_many association thanks to ancestry gem (https://github.com/stefankroes/ancestry)
It works all enough well, but I have this problem:
Task has an association with User, but while active-model-serializers, export user for the main object, it doesn't show user details for also all children.
This is my serializer:
class TaskSerializer < ActiveModel::Serializer
attributes :id, :name, :details, :user_id
belongs_to :user
has_many :children
end
This is my controller:
class Api::V1::TasksController < Api::V1::BaseController
respond_to :json
def index
#tasks = current_user.company.tasks
respond_with #tasks, location: nil
end
end
And this is my model:
class Task < ActiveRecord::Base
has_ancestry
belongs_to :user
end
I've also tried to do this in my model:
class Api::V1::TasksController < Api::V1::BaseController
respond_to :json
def index
#tasks = current_user.company.tasks
render json: #tasks,
each_serializer: TaskSerializer,
status: :ok
end
end
But doesn't work...I've the user details for the parent object, but not for the children(where he only show me user_id, without all User object)
Any suggestions ?
Have you tried adding a serializer for the Children model or querying them as a explicit attribute like so?
class TaskSerializer < ActiveModel::Serializer
attributes :id, :name, :details, :user_id, :children
def children
object.children
end
end
Related
I have following Serializer
class BookSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
I have two method in bookscontroller.rb file as follows:
def index
books = Book.select(:id, :name, :publisher, :publisher, :cover, :author)
if books.present?
render json: books
end
end
def show
book = Book.find_by_id params[:id]
render json: book
end
Actually everything is working fine but the problem is I want chapters records in show page not on index page, but right now query for fetching chapters are running in both action but I only want to include has_many :chapters in show action.
So Is there any way that can I use association for particular method in rails controller?
You can use different serializers for different actions. For example, remove has_many :chapters from BookSerializer and create a separate BookWithChaptersSerializer. Use it as follows:
class BookWithChaptersSerializer < ActiveModel::Serializer
attributes :id, :name, :publisher, :author, :cover_url
has_many :chapters
end
def show
book = Book.find_by_id params[:id]
render json: book, serializer: BookWithChaptersSerializer
end
So I'm having a problem with ams. I'm using Rails 5.2 and I read lots of tutorials and even when I did exactly what they showed I still have something that they don't and I didn't find answer on google.
I have model Course, Video, Quiz and Segment.
Course has many segment, segment can be video or quiz (I'm using sti).
This is how I wrote it:
app/models/course.rb
class Course < ApplicationRecord
validates :title ,presence: true
validates :author ,presence: true
has_many :videos
has_many :quizs
has_many :segments
end
app/models/segment.rb
class Segment < ApplicationRecord
belongs_to :course
end
app/models/quiz.rb
class Quiz < Segment
validates :course_id ,presence: true
validates :name ,presence: true
belongs_to :course
end
app/models/video.rb
class Video < Segment
validates :course_id ,presence: true
validates :name ,presence: true
belongs_to :course
end
app/controllers/courses_controller.rb
class CoursesController < InheritedResources::Base
def show
#course = Course.find(params[:id])
render json: #course.attributes
end
def index
#courses = Course.all
render json: #courses
end
end
app/serializers/course_serializer.rb
class CourseSerializer < ActiveModel::Serializer
attributes :title, :author
has_many :segments
end
and this is what is showed me
I have couple of problems:
I don't know where this data name come from and I don't know how to change it or hide it.
even when I request to see one course I get the created date and other stuff I didn't want, although I configured it so I only see title and author.
I want to know if I can custom the json response so I won't see the title of the relations or change it's name.
You haven't created a SegmentSerializer. By default, AMS will serialize all fields.
class SegmentSerializer < ActiveModel::Serializer
attributes :name
end
Remove the attributes method call. It returns a Hash and then your serializer is not used.
```
class CoursesController < InheritedResources::Base
def show
#course = Course.find(params[:id])
render json: #course
end
def index
#courses = Course.all
render json: #courses
end
end
```
Use the key option
has_many :segments, key: :your_key
I have three models and am trying to output all of them as JSON in a single object.
The models and associations are as follows:
class Customer < ApplicationRecord
has_one :subscription
has_one :address
end
class Address < ApplicationRecord
belongs_to :customer
end
class Subscription < ApplicationRecord
belongs_to :customer
end
I am trying to return all of the associated data as JSON using the following:
class HomeController < ApplicationController
def index
#customers = Customer.all
render json: #customers, :include => :address, :subscription
end
end
However this is returning a syntax error where ruby is expecting => somewhere. Any help on how I can output all of this data would be much appreciated.
Incase anyone is looking I've just answered this question with the following syntax.
class HomeController < ApplicationController
def index
#customers = Customer.all
render json: #customers, :include => [:address, :subscription]
end
end
address and subscription needed to be passed in an array :)
I have two models (Company and User) that have a belongs_to/has_many relationship.
class Company < ActiveRecord::Base
attr_accessor :users_attributes
has_many :users
accepts_nested_attributes_for :users, allow_destroy: true
end
class User < ActiveRecord::Base
belongs_to :company
end
In my CompaniesController I want to create a new instance of Company along with a group of Users.
class Cms::CompaniesController < ApplicationController
def create
company = Company.new(company_params)
respond_to do |format|
if company.save
format.json { render json: company, status: :ok }
else
format.json { render json: company.errors.messages, status: :bad_request }
end
end
end
private
def company_params
params.require(:company).permit(
:id,
:name,
users_attributes: [
:id,
:_destroy,
:first_name,
:last_name,
:email
]
)
end
end
When I call company.save, I would expect a new instance of Company along with several new instances of User to be saved, depending on how many users I have in my params, however no users are persisted.
Here is a sample of what company_params looks like:
{"id"=>nil, "name"=>"ABC", "users_attributes"=>[{"first_name"=>"Foo", "last_name"=>"Bar", "email"=>"foo#bar.com"}]}
What am I missing here?
Remove attr_accessor:
class Company < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users, allow_destroy: true
end
Everything else should work.
--
attr_accessor creates getter/setter methods in your class.
It's mostly used for virtual attributes (ones which aren't saved to the database). Your current setup is preventing you from being able to save the users_attributes param, thus your users are not saving.
For a JSON API, I need to pass url params to my serializes:
http://mydomain.com/api/categories?name=news&counter=123
This is my API controller:
class Api::CategoriesController < ApplicationController
respond_to :json
def index
respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i)
end
end
My serializer looks like this:
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name, :content_counter
has_many :chapters
def chapters
object.chapters.active.with_counter(???)
end
end
In my chapter model I have a scope:
scope :with_counter, lambda { |counter| where("content_counter >?", counter.to_i) }
How can I pass the counter value 123 into (???)
Is that possible?
Any help would be greatly appreciated.
You can pass values to an activemodel serializer using the #options object like this:
class Api::CategoriesController < ApplicationController
respond_to :json
def index
respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i),
counter_value: params[:counter]
end
end
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name, :content_counter
has_many :chapters
def chapters
object.chapters.active.with_counter(#options[:counter_value])
end
end