Rails as_json 包含条件
我在限制动态属性包含的 as_json 时遇到问题:
@pirates_ships = @current_account.pirates.as_json(:include => {:ships => {:only => [:id, :name]}}, :only => [:id, :last_name])
这肯定会给我所有有或没有船只的海盗。
但我还需要通过例如ships.ocean_id来限制船只
我尝试通过包含条件来解决它:
pirates.includes(:ships).where("ships.ocean_id = ?", @ocean.id).as_json(...)
限制有效,但现在所有没有船只的海盗都丢失了。
我自己的 JOIN 语法也没有运气。
有什么想法吗? 嘿
更新
到目前为止我的解决方案是手动预加载。这样我就可以获得动态条件:
@pirates = @current_account.pirates
@ships = @current_account.ships.where({:pirate_id.in => @pirates, :ocean_id => @ocean.id})
render :json => { :pirates => @pirates.as_json(...), :ships => @ships.as_json(...) }
我的 Ajax 回调现在可以迭代 :pirates 并为每个海盗添加他的船只(如果有)。 (我使用 JS 模板引擎客户端从 JSON 响应生成视图)
不是很优雅,但性能对我来说很重要。
我仍然愿意接受更好的想法。 我尝试了动态 has_many :ships, :conditions => ... 但这有点麻烦。
I have problems to restrict an as_json include by a dynamic attribute:
@pirates_ships = @current_account.pirates.as_json(:include => {:ships => {:only => [:id, :name]}}, :only => [:id, :last_name])
This for sure gives me all pirates with or without their ships.
But I also need to restrict the ships by e.g. ships.ocean_id
I tried resolving it by includes with conditions:
pirates.includes(:ships).where("ships.ocean_id = ?", @ocean.id).as_json(...)
The restriction works, but now all pirates without a ship are lost.
Also no luck with my own JOIN Syntax.
Any ideas?
Ahoy
UPDATE
My solution so far is to manually eager load. This way I can have my dynamic conditions:
@pirates = @current_account.pirates
@ships = @current_account.ships.where({:pirate_id.in => @pirates, :ocean_id => @ocean.id})
render :json => { :pirates => @pirates.as_json(...), :ships => @ships.as_json(...) }
My Ajax callback can now iterate over :pirates and add for each pirate his ships if any.
(I use a JS template engine clientside to generate the view from the JSON response)
Not very elegant, but performance is important in my case.
I'am still open for better ideas.
I tried dynamic has_many :ships, :conditions => ...
but that's a bit fiddly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你最好的选择是在从
as_json
生成@pirates_ships
哈希后更改它(我尝试了包含等的多种变体,但没有任何效果) 。I think your best bet would be altering the
@pirates_ships
hash after generating it fromas_json
(I tried multiple variations of includes, etc. and couldn't get anything to work).