我在設置一些模型方法時遇到了RoR中的一些問題。我試圖在一個模型上構建一個方法,其中一個參數被提供一個默認值(nil)。理想的是,如果將值傳遞給方法,它將執行除默認行爲之外的其他操作。下面是設置:方法忽略Ruby on Rails中的參數值,使用默認值代替
我目前有四種模式:市場,交易,商戶和BusinessType
協會是這樣的:
class Deal
belongs_to :market
belongs_to :merchant
end
class Market
has_many :deals
has_many :merchants
end
class Merchant
has_many :deals
belongs_to :market
belongs_to :business_type
end
class BusinessType
has_many :merchants
has_many :deals, :through => :merchants
end
我想拉一些數據基於業務類型(我已經大大簡化了回報,爲簡便起見):
class BusinessType
def revenue(market=nil)
if market.nil?
return self.deals.sum('price')
else
return self.deals(:conditions => ['market_id = ?',market]).sum('price')
end
end
end
所以,如果我這樣做:
puts BusinessType.first.revenue
我得到了預期的結果,即與該業務類型關聯的所有交易的價格總和。然而,當我這樣做:
puts BusinessType.first.revenue(1)
它仍返回所有優惠總和的價格,而不是從市場1.所有優惠總和的價格我也試過:
puts BusinessType.first.revenue(market=1)
還與沒有運氣。
我錯過了什麼?
謝謝!