Ruby on Rails加入JSON输出模型

编程入门 行业动态 更新时间:2024-10-28 06:35:53
本文介绍了Ruby on Rails加入JSON输出模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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 end

app / 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输出模型

本文发布于:2023-10-28 22:36:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   Ruby   Rails   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!