Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-on-rails-2

Convert Rails 2.0.2 action recored query to rails 4.1.5 Rails action recored


I have Sql Query :

@orders = Order.find(
  :all,
  :include => [[:shipping_addresses => :state], :order_status, :order_financial_status],
  :order => 'orders.id DESC',
  :select => ['orders.id, orders.created_at, orders.est_shipping_date, orders.order_contents_count, orders.pdf_filename, order_status.name, order_financial_status.name, shipping_addresses.state_abbr']
)

This is Rails 2.0.2 SQL query this sql fetch all recored from database table "Order" and is using foreign key to fetch other data like shipping address.

I am trying to convert this same query to rails 4.1.5 Action record query .

Order.order("orders.id DESC")

this is giving me the order list but I want to know who i can handle :include and :select part


Solution

  • You can write your code this way and it'll work in Rails < 4 as well:

    orders = Order.
             includes(table_names).
             order(order_columns).
             select(select_columns).
             all
    

    Also, FYI:

    The select clause isn't working like you want it to. To clarify:

    Order.includes(:order_status).select("orders.id")
    

    won't apply any joins. However

    Order.includes(:order_status).select("orders.id, order_statuses.id")
    

    won't apply the select that you want.

    For minimum change in existing code, you should simply remove your select clause because it probably isn't working anyhow.

    Alternatively, if you're ok with the subsequent changes that are required, you could use something like the following:

    orders = Order.
             joins(:order_status). # add more tables & columns like you want
             select("orders.id, order_statuses.name AS order_status_name")
    

    Then you will get your specified columns only. However you'll have to access order_status_name like so:

    orders.first.order_status_name # instead of orders.first.order_status.name
    

    There you go.