Elliot
Elliot

Reputation: 2289

Rails ActiveRecord/SQL Query best practice

I've got a table which has the following columns:

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.

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?

Upvotes: 0

Views: 434

Answers (1)

davidb
davidb

Reputation: 8954

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:

add_column :table_name, :display_time, :timestamp

Then in the model you add attr_reader and attr_accessor for display_time_reader

attr_accessor :display_time_reader
attr_reader :display_time_reader

Then you define the display_time_reader= method:

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. Then you could query:

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

This would be a clean way to deal with this problem!

Upvotes: 2

Related Questions