使用“as_json”时出现问题在我的模型和“渲染:json”中=>在我的控制器(rails)中
我正在尝试创建一个独特的 json 数据结构,但遇到了一个我似乎无法弄清楚的问题。
在我的控制器中,我正在做:
favorite_ids = Favorites.all.map(&:photo_id)
data = { :albums => PhotoAlbum.all.to_json,
:photos => Photo.all.to_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }
render :json => data
在我的模型中:
def as_json(options = {})
{ :name => self.name,
:favorite => options[:favorite].is_a?(Proc) ? options[:favorite].call(self) : options[:favorite] }
end
问题是,rails 对“照片”和“照片”的值进行编码。 'albums'(在我的数据哈希中)作为 JSON 两次,这会破坏一切...我可以让它工作的唯一方法是如果我调用 'as_json' 而不是 'to_json':
data = { :albums => PhotoAlbum.all.as_json,
:photos => Photo.all.as_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }
但是,当我这样做时,我的:最喜欢=> lambda 选项不再将其纳入模型的 as_json 方法......所以,我需要一种方法来告诉“render :json”不要对哈希值进行编码,以便我可以使用“to_json”关于我自己的值,或者我需要一种方法来将参数传递到“as_json”中以实际显示在那里......
我希望这里有人可以提供帮助......谢谢!
I am trying to create a unique json data structure, and I have run into a problem that I can't seem to figure out.
In my controller, I am doing:
favorite_ids = Favorites.all.map(&:photo_id)
data = { :albums => PhotoAlbum.all.to_json,
:photos => Photo.all.to_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }
render :json => data
and in my model:
def as_json(options = {})
{ :name => self.name,
:favorite => options[:favorite].is_a?(Proc) ? options[:favorite].call(self) : options[:favorite] }
end
The problem is, rails encodes the values of 'photos' & 'albums' (in my data hash) as JSON twice, and this breaks everything... The only way I could get this to work is if I call 'as_json' instead of 'to_json':
data = { :albums => PhotoAlbum.all.as_json,
:photos => Photo.all.as_json(:favorite => lambda {|photo| favorite_ids.include?(photo.id)}) }
However, when I do this, my :favorite => lambda option no longer makes it into the model's as_json method.......... So, I either need a way to tell 'render :json' not to encode the values of the hash so I can use 'to_json' on the values myself, or I need a way to get the parameters passed into 'as_json' to actually show up there.......
I hope someone here can help... Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我放弃了......我通过添加自己的数组方法来处理对集合执行操作来解决了这个问题。
Ok I gave up... I solved this problem by adding my own array methods to handle performing the operations on collections.
我认为运行这行代码
等于
换句话说,不要同时使用
to_json
和:json
。I think running this line of code
is equal to
In other words, don't use both
to_json
and:json
.