以前我使用以下代码成功呈现了一个Customer资源,包括它的嵌套Discount资源:
class Discount < ActiveRecord::Base
belongs_to :customer
end
format.json { render json: Customer.find(params[:id]), :include => { :discounts =>
{:include => {...}
}}
}}
我后来在我的折扣中添加了一个范围,即
class Discount < ActiveRecord::Base
belongs_to :customer
scope :current, where('(begin_on <= ? OR begin_on IS NULL) AND (? <= end_on OR end_on IS NULL)', Date.today, Date.today)
end
如何使上述json调用仅渲染当前折扣而不是所有Customer.discounts?
答案 0 :(得分:0)
好的,所以我想出了一个解决方案。我会对任何其他答案感兴趣,但就我的目的而言,这似乎有效:
format.json { render json: @customer, :methods => [:current_discounts]}
class Customer < ActiveRecord::Base
has_many :discounts
def current_discounts
discounts.current
end
end