sqlruby-on-railssqlite3-ruby

Ruby on Rails Database Query with Ruby Variable


This is the current code for my query..

<% property_id = params[:property] %>
<%= property_name = Hotel.find_by_sql('
        SELECT name 
        FROM hotels
    ') %>

I want to be able to add something like

WHERE hotel_id == property_id

But everything I try doesn't seem to work due to the "property_id" portion. I've tried concatenating, different assignments, etc. I feel dumb. SOS. Thank you ahead of time.

Also, when I add..

WHERE hotel_id == "hotelid1"

Which "hotelid1" is an existing hotel_id in the table. It works but not how I would imagine. It returns..

"[#Hotel id: nil, name: "HotelOne">]"

I'm wanting it to only output the hotel name. In this case, HotelOne.


Solution

  • ActiveRecord's where should be suffice for you.

    property_names = Hotel.where(hotel_id: params[:property]).pluck(:name)
    

    And it's confusing to have hotel_id in Hotel model as it contradicts with the default id attribute. Anyhow hope this was useful to you.

    Note: If hotel_id is unique in your table then better to go with @SebastianPalma's comment in your question.