【问题标题】:Append attributes to model object in Rails将属性附加到 Rails 中的模型对象
【发布时间】:2013-02-05 18:06:49
【问题描述】:

我有一个Place 模型和一个PlacesController。目前,控制器使用某些对象响应 JSON。我想为响应的对象添加更多字段。比如我想添加每个地方的标签,通过Place.tags方法查询。

我正在考虑两种解决方案:将对象列表转换为哈希列表并添加我想要的属性,或者在模型中添加一个新列,将其填充到迭代对象列表的控制器中。我不确定是否有更好的方法来做到这一点。

【问题讨论】:

  • 我有点困惑; Places 不是已经与他们的标签关联了吗?

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


【解决方案1】:

我假设:

 class Place < ActiveRecord:Base
   has_many :tags

如果是这样,您是否只是尝试将关联的标签添加到地点对象的 json 中?如果是这样,您可以使用(其中 'place' 是 Place 对象):

 place.to_json(:include=>:tags)

【讨论】:

  • +1;如果模型正确关联(它们应该是),这是正确的答案。
【解决方案2】:

您也可以使用模板来生成 JSON。它可以让您控制 JSON 中显示的内容,并且比通过 to_json 或 render :json 渲染要快得多。

在这里查看我关于呈现 JSON 的最快方法的问题:What is the fastest way to render json in rails

我发现 RABL (https://github.com/nesquena/rabl) 快速且易于设置。

对于您的示例,在 RABL 中,您可以执行以下操作:

class PlacesController < ApplicationController
  def show
    @place = Place.find(params[:id])
  end
end

在视图中:

object @place => :place
attributes :id, :name

children :tags => :tags do
  attributes :id, :name
end

【讨论】:

    【解决方案3】:

    在这种情况下,我可能会使用演示者模式。看这里:http://blog.jayfields.com/2007/03/rails-presenter-pattern.html

    如果您有专业帐户,还有一个 railscast:http://railscasts.com/episodes/287-presenters-from-scratch

    【讨论】:

      【解决方案4】:

      我不确定我的解决方案是否更好

      # in controller
      @place = Place.first
      @place[:place_tags] = @place.tags.map(&:attributes)
      render :json => @place
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多