我正在尝试使用Ruby on Rails构建JSON API端点。
I'm trying to build a JSON API end point with Ruby on Rails.
我按照以下说明进行操作,并能够为我的模型创建JSON API railscasts/episodes/350-rest-api-versioning?view=comments/
I followed the instruction in the following and was able to create JSON API for my models railscasts/episodes/350-rest-api-versioning?view=comments/
我有以下控制器:
/api/v1/movies_controller.rb
/api/v1/movies_controller.rb
class MoviesController < ApplicationController def index if params[:p].nil? p = 1 else p = params[:p].to_i end @movies = Movie.order("id DESC").page(p) end def show @movie = Movie.find(params[:id]) end end我需要将其与流派对象一起加入,其中Movie has_many:genres和流派属于_movie
I need to join this with the Genre object where Movie has_many :genres, and Genre belongs_to :movie
但是,我无法使用以下内容将流派与电影对象结合在一起以用于JSON输出:
However, I'm not able to use the following to get the genres joined with the movie object for the JSON output:
@movie = Movie.find(params[:id], :joins => :genres)我确实注意到以下命令能够在ruby控制台中生成合并的输出
I did notice that the following command is able to generate the joined output in ruby console
@movie.to_json(:include=>:genres)但是在控制器中添加它不会t显示其他类型字段
But then adding this in the controller doesn't show the additional genres fields
有人可以帮我吗?
谢谢!
推荐答案我的adv ise:使用 active_model_serializers
My advise: Go with active_model_serializers
将以下行添加到您的Gemfile
Add the following line to your Gemfile
gem 'active_model_serializers'执行捆绑安装。
在那之后执行
rails g serializer movie rails g serializer genre比自定义以下代码:
/api/v1/movies_controller.rb
class MoviesController < ApplicationController respond_to :json def index if params[:p].nil? p = 1 else p = params[:p].to_i end @movies = Movie.order("id DESC").page(p) respond_with @movies end def show @movie = Movie.find(params[:id]) respond_with @movie end end应用/serializers/movie_serializer.rb
class MovieSerializer < ActiveModel::Serializer embed :ids, :include => true attributes :id, :name has_many :genres endapp / serializers / genre_serializer.rb
class GenreSerializer < ActiveModel::Serializer embed :ids, :include => true attributes :id, :name end有在中查看 active_model_serializers 的完整文档 github/rails-api/active_model_serializers
更多推荐
Ruby on Rails加入JSON输出模型
发布评论