[英]Ruby on Rails 4 render :json with conditions
I have this render expression in a Ruby on Rails 4 controller: 我在Ruby on Rails 4控制器中有此渲染表达式:
render :json => @account_preferences, :include => {:payment_methods => {:include => {:payment_type => {:only => [:id, :name]}}}}
Can I filter the payment_methods somehow in this expression to get only the payment_methods with state = 'Confirmed'? 我是否可以在此表达式中以某种方式过滤payment_methods,以仅获取state =“ Confirmed”的payment_methods?
If you do a lot of includes and conditionals I'd recommend using jbuilder to do this kind of stuff. 如果您要进行很多包含和条件操作,我建议您使用jbuilder进行此类操作。 Did you take a look at that?
你看了吗? https://github.com/rails/jbuilder
https://github.com/rails/jbuilder
It's included in your Gemfile by default in a rails 4 project. 默认情况下,它包含在您的Gemfile中的rails 4项目中。
I don't believe you can do this conditionally in the render :json. 我不相信您可以在render:json中有条件地执行此操作。 But something like this would work:
但是这样的事情会起作用:
class AccountPreference < ActiveRecord::Base
has_many :confirmed_payment_methods,-> { where state: 'Confirmed' }, class_name: 'PaymentMethod'
end
and call that association in your to_json 并在您的to_json中调用该关联
render :json => @account_preferences, :include => {:confirmed_payment_methods => {:include => {:payment_type => {:only => [:id, :name]}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.