簡體   English   中英

Rails中的無表模型JSON序列化

[英]Tableless model JSON serialization in Rails

我有無表模型(如#219 railscast中所示):

class MyModel
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :attr1, :attr2, :attr3, :attr4

  private
    def initialize(attr1 = nil)
      self.attr1 = attr1
    end

    def persisted?
      false
    end
end

然后我嘗試在控制器中呈現JSON:

@my_model = MyModel.new
render json: @my_model.to_json(only: [:attr1, :attr2])

但它使用模型的所有屬性呈現JSON。

我嘗試添加

include ActiveModel::Serialization

但它並沒有更改呈現的JSON。

如何僅使用無表模型的必要屬性來呈現JSON?

我正在使用Rails 3.2.3

更新

多謝你們。 看來您幾乎是正確的。 我結合了您的解決方案,並得到了:

模型:

include ActiveModel::Serialization

...

def to_hash
  {
    attr1: self.attr1,
    attr2: self.attr2,
    ...
  }
end

控制器:

render json: @my_model.to_hash.to_json(only: [:attr1, :attr2])

我真的不知道該接受誰的答案。

更新2

突然出現了新的陌生感。 屬性之一是哈希數組。 就像這樣:

attr1: [[{name: "name", image: "image"}, {name: "name", image: "image"}],
        [{name: "name", image: "image"}, {name: "name", image: "image"}]]

但是現在它丟失了所有內容,看起來像這樣:

attr1: [[{}, {}], [{}, {}]]

也許有人知道如何解決?

更新3 :)

Erez Rabih的回答很有幫助。 使用slice代替to_json解決了該問題。 因此,最終的解決方案是:

render json: @my_model.to_hash.slice(:attr1, :attr2)

我知道這不是直接的,但是如何:

render :json => @my_model.attributes.slice(:attr1, :attr2)

您還需要將屬性方法定義為:

def attributes
   {:attr1 => self.attr1.....}
end

感謝您的評論。

我相信這是因為Object :: as_json在內部調用(請看此: http ://apidock.com/rails/Object/as_json),並且它沒有像:only或:except這樣的選項,因此您可以覆蓋to_hash方法您的課程,例如:

def to_hash
  {:attr1 => self.attr1, :attr2 => self.attr2}
end

和to_json將完全按照您的要求進行。

當然,另一個選擇是重寫方法to_json ...

您可以將初始方法(包括AM序列化模塊)與Erez的方法混合使用,如文檔所示。

class MyModel
    include ActiveModel::Serialization::JSON
    ....
    def attributes
       {:attr1 => self.attr1.....}
    end
    ...
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM