Ruby on rails 为模型定义几种json格式

Ruby on rails 为模型定义几种json格式,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,在我的rails应用程序中,我在模型中定义了一种特定的JSON格式: def as_json(options={}) { :id => self.id, :name => self.name + ", " + self.forname } end 在控制器中,我只需调用: format.json { render json: @patients} 所以现在我尝试为不同的操作定义另一种JSON格式,但我不知道如何定义?

在我的rails应用程序中,我在模型中定义了一种特定的JSON格式:

def as_json(options={})
     { 
         :id => self.id,
         :name => self.name + ", " + self.forname
     } 
end
在控制器中,我只需调用:

 format.json { render json: @patients}
所以现在我尝试为不同的操作定义另一种JSON格式,但我不知道如何定义?
如何将另一个定义为_json,或者如何将变量传递给
作为_json
?谢谢这是一个非常难看的方法,但您可以重构它以获得更好的可读性:

def as_json(options={})
  if options.empty?
    { :id => self.id, :name => self.name + ", " + self.forname }
  else
    if options[:include_contact_name].present?
      return { id: self.id, contact_name: self.contact.name }
    end
  end
end

好的,我应该给你一段更好的代码,这里是:

def as_json(options = {})
  if options.empty?
    self.default_json
  else
    json = self.default_json
    json.merge!({ contact: { name: contact.name } }) if options[:include_contact].present?
    json.merge!({ admin: self.is_admin? }) if options[:display_if_admin].present?
    json.merge!({ name: self.name, forname: self.forname }) if options[:split_name].present?
    # etc etc etc.

    return json
  end
end

def default_json
  { :id => self.id, :name => "#{self.name}, #{self.forname}" }
end
用法:

format.json { render json: @patients.as_json(include_contact: true) }

通过“as_json”方法定义散列结构,在各自的模型类中,即(示例1)中的用户模型中,它成为json格式的活动记录(即用户)的默认散列结构。它不能被示例2中定义的任何内联定义覆盖:2

class UserController < ApplicationController
 ....
  def create 
    user = User.new(params[:user])
    user.save
    render json: user.as_json( only: [:id, :name] )
  end
end
例1:

class User < ActiveRecord::Base
 .....
  def as_json(options={})
    super(only: [:id, :name, :email])
  end
end
class用户
示例:2

class UserController < ApplicationController
 ....
  def create 
    user = User.new(params[:user])
    user.save
    render json: user.as_json( only: [:id, :name] )
  end
end
class UserController
因此,在本例中,当执行创建操作时,“用户”以(“仅:[:id,:name,:email]”格式返回,而不是以(“仅:[:id,:name]”格式返回)

因此,options={}被传递给as_json方法,为不同的方法指定不同的格式

最佳实践是将散列结构定义为常量,并在需要时调用它

比如说 Ex:models/user.rb 这里,常量是在模型类中定义的

class User < ActiveRecord::Base
...
...
 DEFAULT_USER_FORMAT  = { only: [:id, :name, :email] }
 CUSTOM_USER_FORMAT = { only: [:id, :name] }
end
class用户
Ex:controllers/user.rb

class UserController < ApplicationController
 ...
  def create
  ...
  render json: user.as_json(User::DEFAULT_USER_FORMAT)
  end

  def edit
  ...
  render json: user.as_json(User::CUSTOM_USER_FORMAT)
  end
end
class UserController

您可以将变量传递给as_json:
{render json:@patients.as_json(include_relation:true)}
,并根据选项定义您自己的条件OK,但我想我还需要其他东西?我发布了一个答案,有点混乱,但您明白了,请不要犹豫询问任何有关它的问题;)谢谢你,我会试试的!1分钟后我会打破你的12k!