0

以前我使用下面的代码成功地呈现了一个客户资源,包括它的嵌套折扣资源:

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?

4

1 回答 1

0

好的,所以我想出了一个解决方案。我会对任何替代答案感兴趣,但就我的目的而言,这似乎可行:

format.json { render json: @customer, :methods => [:current_discounts]}

class Customer < ActiveRecord::Base
  has_many :discounts

  def current_discounts
    discounts.current
  end
end
于 2012-08-23T03:15:16.363 回答