【问题标题】:Multiple conditions within a scope rails 4范围内的多个条件 rails 4
【发布时间】:2013-12-13 10:10:59
【问题描述】:

我正在尝试编写一个可以从两个模型中获取数据的范围,以前没有这样做过,所以看看是否有人可以在理论和实践方面帮助我。

我的两个模型是这样定义的

class Member < ActiveRecord::Base
belongs_to :membership
accepts_nested_attributes_for :membership

attr_accessible :membership_id, :forename, :middlename, :surname, :house_no, :house_name, :street, :town, :postcode, :home_tel, :mobile_tel, :work_tel, :email, :start_date, :expiry_date
end

class Membership < ActiveRecord::Base
has_many :members, :dependent => :destroy
attr_accessible :membership_type, :cost 
end

我想让今天加入的所有成员整理它产生的总金额,以英镑为单位

那么我可以在范围内执行求和,还是必须编写一个获取总数的方法,然后在范围内使用该方法?

class Member < ActiveRecord::Base

scope :new_memberships_cash_today, ->() {
where(:start_date => Date.today)
}

end

就我目前所知,不正确我知道。真的不知道如何构建其余部分,感谢任何帮助

【问题讨论】:

    标签: ruby-on-rails ruby scope ruby-on-rails-4


    【解决方案1】:

    我认为这样就足够了:

    joins(:memberships).where(:start_date => Date.today).sum('memberships.cost')
    

    【讨论】:

    • 啊,我明白了,谢谢,虽然我得到未定义的方法 `to_key' 因为值存储为浮点数而不是整数..有什么想法吗?
    • 你使用什么数据库? MySQL,Postgres?
    • 我有一种感觉,你使用了错误的列类型,因为这假设工作。但作为一个丑陋的选择,你可以尝试这样的事情:joins(:memberships).where(:start_date =&gt; Date.today).select('memberships.cost').map(&amp;:cost).inject(:+).select('ROUND(SUM(memberships.cost), 2)')
    • 好吧,我在考虑列类型,我使用诸如 17.99 和 19.99 之类的值,所以整数会将这些数字向下舍入不是吗?
    • 使用小数(5,2)或类似的东西:)
    猜你喜欢
    • 2015-02-14
    • 2014-10-04
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2017-06-25
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多