简体   繁体   English

Rails ActiveRecord / SQL查询最佳实践

[英]Rails ActiveRecord/SQL Query best practice

I've got a table which has the following columns: 我有一个包含以下列的表:

  • show_days_before_start (integer) show_days_before_start(整数)
  • start_time (DATETEXT) start_time(DATETEXT)

The purpose of the "show_days_before_start" column is to add the days onto the "start_time" to determine when the record should start appearing in results (if it's outside of this time then it should not be shown) (this column could have value from 7 to 21), and the "start_time" is just a datetime stamp of when the event the record is referring to starts. “show_days_before_start”列的目的是将日期添加到“start_time”以确定记录何时应该开始出现在结果中(如果它超出此时间则不应显示)(此列可能具有7的值)到21),“start_time”只是记录所指的事件开始时的日期时间戳。

I need a query to do the above and to return the relevant records. 我需要一个查询来执行上述操作并返回相关记录。 What is the best way to approach this in terms of query design? 在查询设计方面,最好的方法是什么?

This is the wrong way to do it. 这是错误的做法。 You should generate the show date when inserting the dataset to the database! 将数据集插入数据库时​​应生成显示日期! Add a column called display_time : 添加一个名为display_time的列:

add_column :table_name, :display_time, :timestamp

Then in the model you add attr_reader and attr_accessor for display_time_reader 然后在模型中为display_time_reader添加attr_readerattr_accessor

attr_accessor :display_time_reader
attr_reader :display_time_reader

Then you define the display_time_reader= method: 然后定义display_time_reader=方法:

def display_time_reader=(days_before_start)
     self.display_time=self.start_time-days_before_start.days
end

Then you add a text_field :display_time_reader (You can also take a dropdown with values 7..21) to your _form.html.erb and when you enter 5 it will save the start_date - 5 days to the display_time field. 然后添加一个text_field :display_time_reader (您也可以将值为7..21的下拉列表)添加到_form.html.erb ,当您输入5时,它会将start_date - 5天保存到display_time字段。 Then you could query: 然后你可以查询:

ModelName.where("display_time > ?", Time.now) 

This would be a clean way to deal with this problem! 这将是一个处理这个问题的干净方法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM