Kingsley Simon
Kingsley Simon

Reputation: 2210

Rails Joins query not responding like SQL Join query

I have two tables, package and time_slot and i want to join and return some values

in my package.rb

class Package < ActiveRecord::Base
    attr_accessible :company_id, :time_slot_id, :location_id, :service_id, :day_id, :resource_quantity, :package_category_id, :time_slot, :is_booked
    belongs_to :time_slot
end

in my time_slot.rb

class TimeSlot < ActiveRecord::Base
    attr_accessible :start_time, :end_time
    has_many :package
end

in my sql query when i do run this query, it works perfectly

SELECT packages.id, time_slots.start_time, time_slots.end_time FROM packages INNER JOIN time_slots ON packages.time_slot_id = time_slots.id;

this is the result enter image description here

But when i run the same query in Rails c

Package.joins("LEFT JOIN time_slots ON packages.time_slot_id = time_slots.id").select("packages.id, time_slots.start_time, time_slots.end_time")

it only returns this

 #<ActiveRecord::Relation [#<Package id: 1>, #<Package id: 2>, #<Package id: 3>]>

Any one knows why? Any help appreciated

Upvotes: 0

Views: 80

Answers (1)

Pavling
Pavling

Reputation: 3963

It doesn't "return" that. That's the to_s representation of what it does return.

The Package model doesn't have a start_time or end_time attribute, so the console doesn't show the selected values when inspecting the relation.

But each of those objects will return those values when called. Run your query again and try adding:

.first.start_time

Or

.map(&:attributes)

Upvotes: 2

Related Questions