7

I need this SQL query Rails-friendly:

SELECT *,
IF (store.availability_offset IS NULL, DATE_ADD(product.release_date, INTERVAL 0 DAY), DATE_ADD(product.release_date, INTERVAL store.availability_offset DAY))
FROM products JOIN stores ON product.store_id = stores.id
WHERE (DATE_ADD(products.release_date, INTERVAL stores.availability_offset DAY) BETWEEN '2013-06-12' AND '2014-07-12' OR DATE_ADD(products.release_date, INTERVAL 0 DAY) BETWEEN '2013-06-12' AND '2014-07-12');

This is my Rails query up to now:

@products = Product.joins(:store).where("products.release_date >= :start_date AND products.publishing_date <= :end_date)", :start_date => params[:search][:start_date], :end_date => params[:search][:end_date]")

What I want to do:

  • implement the IF conditional in order to manage the stores availability_offset in case its value is NULL.

  • implement the DATE_ADD() function to be able to add the availability_offset value to the date release date.

How can I do that without using SQL sintax, just ActiveRecord? Thank you!

5
  • What is your Database engine name ? Commented May 21, 2015 at 11:09
  • Hi, I work with MySQL. Commented May 21, 2015 at 11:11
  • I also need a DATE_ADD in Ruby (not Rails though) - bounty added Commented Oct 26, 2015 at 20:02
  • Can you post your migrations? Commented Oct 28, 2015 at 10:21
  • Have you considered storing 0 instead of NULL in 'store.availability_offset' ? Commented Nov 2, 2015 at 16:32

2 Answers 2

1

You just copy your select of SQL into Rails ActiveRecord select. Try to do this:

@products = Product.select('products.*, IF(store.availability_offset IS NULL, DATE_ADD(products.release_date, INTERVAL 0 DAY), DATE_ADD(products.release_date, INTERVAL stores.availability_offset DAY)) AS store_availability_offset')
    .joins(:store).where("products.release_date >= :start_date AND products.publishing_date <= :end_date)", :start_date => params[:search][:start_date], :end_date => params[:search][:end_date]")

For your if statement in select, I use alias column into store_availability_offset. I hope this help you.

Sign up to request clarification or add additional context in comments.

Comments

1

I would place the if conditional and the date_add() in the Product class, override the release_date attribute and keep the ActiveRecord query as you wrote it:

class Product < ActiveRecord::Base

  def release_date
    read_attribue(:release_date) + (availability_offset ||0)
  end

end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.