【问题标题】:AwesomeNestedSet, virtual attribute and JSON outputAwesomeNestedSet、虚拟属性和 JSON 输出
【发布时间】:2013-09-08 21:06:09
【问题描述】:

我有这个模型:

class MenuItem < ActiveRecord::Base
  attr_accessor :name_with_level
  acts_as_nested_set # AwesomeNestedSet gem

  def self.nested_names
    self.each_with_level(MenuItem.order(:lft)) do |menu_item, level|
      name = "- " * level + menu_item.name
      menu_item.name_with_level = name
    end
  end
end

来自控制器的操作:

def list
  menu_items = MenuItem.all
  render :json => {:items => menu_items}
end

如何在输出 JSON 中包含 name_with_level 并一击 DB?

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    我相信这个 SO 答案会有所帮助:Including a virtual attribute in the respond_with hash

    在你的情况下:

    MenuItem
    
    def as_json(options = {})
      super.as_json(options).merge(name_with_level: name_with_level)
    end
    

    这是一种简单的方法,假设您希望所有 menu_items 都以自己的 JSON 样式表示返回此虚拟属性。否则,您需要自己构建 ruby​​ 哈希,为每个 menu+item 包含 name_with_level,然后为整个事情添加 .to_json

    【讨论】:

    • 或者使用自己的方法:as_json(methods: :method_name)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多