如何获取当月创建的记录?
我有一个有很多选票的候选人。
我想获得当月创建的候选人的投票?
@candidate.votes.from_this_month scope :from_this_month, where("created_at > ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)
这给了我一个PG错误:PG ::错误:错误:列引用\“created_at \”是不明确的
如果我试试
scope :from_this_month, where("vote.created_at > ? AND vote.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)
我收到以下错误
PG::Error: ERROR: missing FROM-clause entry for table "vote"
您还需要将其放在lamda中。
scope :from_this_month, lambda { where("votes.created_at > ? AND votes.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month) }
否则它似乎可以工作,你的测试都会通过,但如果你的应用程序运行超过一个月,你将开始得到不正确的结果,因为Time.now在类加载时进行评估,而不是在调用方法时。
正确的范围
scope :from_this_month, lambda {where("votes.created_at > ? AND votes.created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)}
这是因为在轨道中,模型名称是单数的(即Vote
),并且通过对流创建的表格是pural(例如votes
)
编辑
这可以用lambda {where(created_at: Time.now.beginning_of_month..(Time.now.end_of_month))}
更简单地编写,我们需要使用lambda,因为下面的注释给出了原因。
Thanx BroiSatse提醒:D
您可以使用ActiveRecord Association Extension :
#app/models/Candidate.rb Class Candidate < ActiveRecord::Base has_many :votes do def from_this_month where("created_at > ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month) end end end
这应该允许您调用@candidate.votes.from_this_month
来返回所需的条件数据
- 奇怪的Heroku浮点精度错误(轨道上的ruby)
- Rails通过现有数据库进行迁移
- Heroku上的Rails 3.1中的Postgres重音不敏感LIKE搜索
- 在PostgreSql中有关联的子句
- Cloud9 postgres
- 如何将PGSeaerch结果链接到嵌套资源中的索引页面?
- Rails 3:在Postgres支持的ActiveRecord中使用json作为列类型时出现迁移错误
- Rails 4 – 使用postgres逐个渲染数组值
- 计算Active Admin仪表板(Rails,Active admin 1.0,Postgresql数据库,postgres_ext gem)中序列化属性(数组)中值的出现次数