簡體   English   中英

Ruby - 如何根據列條件篩選 SQLite 行

[英]Ruby - How to filter SQLite rows based on column conditions

我有一個變量session[:pet_profile_tags]返回一個像["adult", "activity_low", "overweight"].

然后我有一個名為 balto.db 的 SQLite 數據庫,其中包含表 pet_tips。 該表包含 2 列,“ID”(整數)和“C1_inclusion”(VARCHAR)。

對於 pet_tips 表的每一行,我需要檢查C1_inclusion列中包含的值是否包含session[:pet_profile_tags]數組變量的值之一。 如果是這種情況,我需要檢查行的 ID 並將其存儲在另一個名為pet_tips的數組變量中。

我嘗試了以下代碼,但出現以下錯誤: TypeError - no implicit conversion of String into Integer: index.rb:428:in '[]' ,第 428 行是if (session[:pet_profile_tags].include?(row["C1_inclusion"].to_s))

        # Assign pet tips
        pet_tips = []

        # Query the pet_tips table
        db = SQLite3::Database.open "balto.db"
        rows = db.execute("SELECT * FROM pet_tips")

        # Iterate through each row of the table
        rows.each do |row|
          # Check if the row matches the C1_inclusion column
          if (session[:pet_profile_tags].include?(row["C1_inclusion"].to_s))
            # If the row matches, add the ID to the pet_tips array
            pet_tips << row["ID"]
          end
        end
        session[:pet_tips] = pet_tips
        db.close

我已經被困了幾個小時,非常感謝任何幫助!

首先,我嘗試返回 session[:pet_profile_tags] 變量的值以確保我獲得了正確的數組。 然后,我確保檢查我的代碼中是否正確引用了不同的列和變量名稱。

錯誤

您的錯誤在這里: row["C1_inclusion"]

  • row是按列順序排列的值Array ,例如[1,"adult"]

  • Array#[]需要一個Integer (索引),但您使用String ("C1_inclusion") 調用它

解決方案

要解決這個問題,您可以

方案一:根據列序使用Integer索引

if (session[:pet_profile_tags].include?(row[1]))
  pet_tips << row[0]
end

選項 2:將行轉換為Hash

總是:

db = SQLite3::Database.open "balto.db"
db.results_as_hash
rows = db.execute("SELECT * FROM pet_tips")
rows.each do |row|
  if (session[:pet_profile_tags].include?(row["C1_inclusion"]))

只是為了這個循環:

rows.each_hash do |row|
  if (session[:pet_profile_tags].include?(row["C1_inclusion"]))

選項 3:只查詢您想要的數據。

# Query the pet_tips table
db = SQLite3::Database.open "balto.db"
session[:pet_tips] = db.prepare("SELECT ID FROM pet_tips WHERE pet_tips.C1_inclusion IN (?)")
  .execute!(session[:pet_profile_tags].map {|s| "'#{s}'"}.join(","))
  .flatten
db.close

這使用session[:pet_profile_tags]作為pet_tips.C1_inclusion的 WHERE 條件,並假設您可以控制此變量(例如不執行轉義)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM