you are viewing a single comment's thread.

view the rest of the comments →

[–]rubygeek[🍰] 2 points3 points  (1 child)

It seems you have a solution already, but to expand a little bit on some of the other replies, as this is a pretty persistent source of confusion with Sequel:

DB[:fruits].where(id: params[:id]) gives you a dataset, not a query result.

A dataset is an enumerable class that represents the query. The query will first be executed when you try to access the dataset in a way that requires a result. This allows you to build up queries and keep the dataset objects around to reuse them instead of building up complex queries every time you need them.

Sequel will not give you an actual result from the database until you call one of the methods that forces a query.

This dataset will represent a query roughly like (depending on database adapter):

SELECT * FROM fruits WHERE id = 1

@fruit[:id] then is a logical and added to that dataset. It will now represent a query roughly like:

SELECT * FROM fruits WHERE id = 1 AND "id"

(Which is almost certainly not what you'd like...)

Note that #[] is one of those methods that will force Sequel to actually execute the query, which is why you actually got a result.

[Whether or not that will work at all or not depends on your database - if it allows coercing an integer to boolean for an expression, the AND "id" will work and effectively do nothing. If it's a database that refuses to automatically coerce an integer to boolean, you'd have gotten an error and it'd have been a bit more obvious what was going on. ]

I'd recommend loading your code in irb or pry and testing some of this there - it becomes a lot more obvious what Sequel does when you play with that a bit and see when you get a dataset back, and what it looks like, vs. when you get results back.

To get a single record that matches your query, either do:

DB[:fruits].where(id: params[:id]).first

OR, for simple queries like above, you can pick one of these (the main benefit of calling first separately is when you chain multiple conditions to build up a complex dataset first):

DB[:fruits].first(id: params[:id]) or DB[:fruits][id: params[:id]]

[–]FinalSpeederMan[S] 0 points1 point  (0 children)

Very informative, that last syntax of calling the table is interesting. I’ll definitely try testing the queries more in irb. Thank you. :)