简体   繁体   中英

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 .

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.

我想你正在寻找这个。

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

尝试以下行:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM