【问题标题】:rails render json add custom attributerails render json 添加自定义属性
【发布时间】:2014-12-08 19:49:40
【问题描述】:

我有一个方法调用:

def group
    render :json => Group.find(params[:id])
end

呈现:

{
  id: 1,
  name: "Name Here",
  description: "Description Here",
  created_at: "2014-11-24T19:10:53.609Z",
  updated_at: "2014-11-24T19:10:53.609Z"
}

我还想为正在呈现的组模型附加一个自定义属性。例如,我希望 JSON 组包含属性 message : "Hello World"

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4


    【解决方案1】:

    向我的模型添加一个名为message 的方法,该方法返回一个字符串,然后调用,

    render :json => Group.find(params[:id]), :methods => :message 
    

    成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-05
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多