Haha
Haha

Reputation: 448

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.

Upvotes: 0

Views: 114

Answers (3)

Prabakaran
Prabakaran

Reputation: 353

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.

Upvotes: 1

Ankur Shukla
Ankur Shukla

Reputation: 365

Try the below line :-

<% property_name = ActiveRecord::Base.connection.execute("SELECT name FROM hotels WHERE hotel_id=#{property_id}").first["name"] %>

Upvotes: 0

MD Tawab Alam Khan
MD Tawab Alam Khan

Reputation: 188

I think you are looking for this.

<%= property_name = Hotel.find_by_sql("SELECT name FROM hotels WHERE hotel_id=#{ruby_variable}") %>

Upvotes: 0

Related Questions