I'm making api with rails, but I can't design it the way I want to, so I'd like to ask you a question.I'd like to get multiple Item models in Tag models including item model like_users (users who like Item).In the end, I would like to obtain it as follows.
{tags:[
{ "id"—1,
"name"—Mens,
"items": [
{
"id"—1,
"name"—Shirts,
"like_users":[
{
"id"—1,
"name"—Tom
},
{
"id"—2,
"name"—Steve
}
]
}
]
}
]
}
The current code is
models/tag.rb
class Tag<ActiveRecord::Base
has_many —Items
end
models/item.rb
class Item<ActiveRecord::Base
has_many:like,dependent::destroy
has_many:like_users,through::like,source::user
end
models/user.rb
class User<ActiveRecord::Base
has_many:like,dependent::destroy
has_many:like_items, through::like,source::item
end
models/like.rb
class Like <ActiveRecord::Base
belongs_to —Item
belongs_to —user
end
app/apis/api/v1/tags.rb
module API
module V1
class Tags <Grape::API
resource —tags do
desc 'GET/api/v1/tags/:id'
params do
require: id, type: Integer, desc: "Tagid."
end
get' of : id'do
tag = Tag.find (params[:id])
@tag=tag.items.#I don't know how to write this line.
end
end
end
end
end
If you don't mind, could someone please reply?Thank you for your cooperation.
ruby-on-rails ruby api
It's Sumimasen.I realized later that I was using Grape.
I don't know how to do Grape, so please look forward to hearing from someone else.
Rails will understand, so I'll just post a hint.
I hope it will be helpful.
[3]pry(main)>tag.as_json(root:true, include:{items:{include::like_users}})
{
"tag" = > {
"id" = > 1,
"name" = > "Men",
"items" = > [
[0] {
"id" = > 1,
"tag_id" = > 1,
"name" = > "shirts",
"like_users" = > [
[0] {
"id" = > 1,
"name" = > "Tom"
},
[1] {
"id" = > 2,
"name" = > "Steve"
}
]
}
]
}
}
© 2024 OneMinuteCode. All rights reserved.