Question

I am trying to retrieve data from a PostgreSQL database with Sequel in Sinatra.

DB = Sequel.connect('postgres://connection_data')
items = DB[:items]

Then I try to get an entry with a specific ID:

get '/:id' do
   @item = items.filter(:id => params[:id]) 
   erb :edit
end

In my edit view I would like to display the content of the @item variable. The problem is that I don´t know how to get for example the ID.

<% if @item %>
   <a href="/<%= @item.id %>/doit">Do something</a>
<% else %>
   <p>Item not found.</p>
<% end %>

I tried using @item.id and @item[:id] but both don´t work. I get an error undefined method 'id' for #<Sequel::Postgres::Dataset:0x007fac118b7120>. What would be the right way to retrieve the values from the @item variable?

Was it helpful?

Solution

@item = items.filter(:id => params[:id]) returns a dataset. If you want a single item, you should do: @item = items.first(:id => params[:id].to_i)

Also @item.id is probably not want you want. Given that items = DB[:items], you are using a plain dataset and then @item = items.first(:id => params[:id].to_i) is going to give you a hash. You need to do @item[:id] to get the item's id.

You may want to look at using models instead:

# model file
class Item < Sequel::Model; end

# sinatra code
@item = Item[params[:id].to_i]

# template
@item.id

OTHER TIPS

Actually @item.id is the right way. The only problem I can see in your code is

@item = items.filter(:id == params[:id]) 

which should be

@item = items.filter(:id => params[:id].to_i) 

EDIT:

Try this:

@item = items.where(:id => params[:id].to_i)

@item.select(:id) #to embed

params[:id] is giving a string, so convert it to an integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top