Rails中的无表模型JSON序列化 [英] Tableless model JSON serialization in Rails
问题描述
我有一个无桌子的模型(就像在#219 railscast中显示的那样):
I have tableless model (like it was shown in #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:
Then I'm trying to render JSON in controller:
@my_model = MyModel.new
render json: @my_model.to_json(only: [:attr1, :attr2])
但是它使用模型的所有属性呈现JSON.
but it renders JSON with all the attributes of the model.
我尝试添加
include ActiveModel::Serialization
但它并没有更改呈现的JSON.
but it didn't change rendered JSON.
如何仅使用无表模型的必要属性来呈现JSON?
How can I render JSON with only necessary attributes of my tableless model?
我正在使用Rails 3.2.3
I'm using Rails 3.2.3
更新
谢谢,伙计们.看来您几乎是正确的.我结合了您的解决方案并得到了:
Thanks, guys. It seems you're all almost right. I combined your solutions and got this:
型号:
include ActiveModel::Serialization
...
def to_hash
{
attr1: self.attr1,
attr2: self.attr2,
...
}
end
控制器:
render json: @my_model.to_hash.to_json(only: [:attr1, :attr2])
我真的不知道谁的答案会被接受.
I really don't know whose answer to be accepted.
更新2
突然出现了新的陌生感.属性之一是哈希数组.就像这样:
Suddenly new strangeness appeared. One of the attributes is array of hashes. It was like this:
attr1: [[{name: "name", image: "image"}, {name: "name", image: "image"}],
[{name: "name", image: "image"}, {name: "name", image: "image"}]]
但是现在它丢失了所有内容,看起来像这样:
But now it lost all its content and looks like this:
attr1: [[{}, {}], [{}, {}]]
也许有人知道如何解决?
Maybe anyone know how to fix it?
更新3 :)
Erez Rabih的回答有所帮助.使用slice
代替to_json
解决了该问题.因此,最终的解决方案是:
Erez Rabih's answer helped. Using slice
instead of to_json
solved the problem. So, final solution is:
render json: @my_model.to_hash.slice(:attr1, :attr2)
推荐答案
我知道这不是直截了当的,但是如何:
I know it isn't straight forward but how about:
render :json => @my_model.attributes.slice(:attr1, :attr2)
还需要将属性方法定义为:
You will also be required to define an attributes method as:
def attributes
{:attr1 => self.attr1.....}
end
感谢评论者.
这篇关于Rails中的无表模型JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!