Satchel
Satchel

Reputation: 16724

ActiveRecord query getting back ActiveRecord:Relation

I get back for one query an ActiveRecord:Realtion, with another query parameter I get back the right array as expected and as desired.

How do I get the array when passing in a value for the bot_client_id, and why would the behavior be different?

[20] pry(#<BotResponse>)> e = Event.where.has {(bot_client_id == 'aiaas-1409611358153-user-0147')}
=> #<Event::ActiveRecord_Relation:0x15fe2a8>

[21] pry(#<BotResponse>)> Event.where.has {(status == 'inactive')}.first
=> #<Event:0x00000002ae1d50
 id: 1,
 bot_client_id: "aiaas-1409611358153-user-0147",
 keyword: "testing create event 1 minute from now",
 topic: nil,
 status: "inactive",
 channel: "telegram",
 created_date: 2017-05-06 20:37:24 UTC,
 tickle_expression: nil,
 time_of_day: "1 minute from now",
 next_occurrence: 2017-05-06 20:54:20 UTC,
 time_zone: nil,
 recurring: false>

Upvotes: 0

Views: 90

Answers (1)

spickermann
spickermann

Reputation: 106782

The Active Record query interface returns a relation for almost every method call. this allows to chain method calls like Foo.where(bar: true).join(:baz).order(:id).

Another advantage is that it doesn't run the query against the database immediately, but when the result is actually needed for the first time. Rails loads the record when you call certain methods on a relation, like each, map, count, to_a, load or first.

So the important difference between your example is not the bot_id or the status, but that you call first in your second example, but no method that would load the records from the database in your first example.

Upvotes: 2

Related Questions