2016-03-07 98 views
0

我很不熟悉MySQL查詢,但我目前正在學習它們。我如何找到對象的所有nil字段,然後填充這些字段中的一個?Ruby on rails MYSQL查詢

例如,我有一個庫存 - 但我想找到所有的空插槽以顯示我留下了多少個插槽,然後找到空的插槽,然後僅填充字符串中的一個字段或編號。

我該怎麼做?

這是我嘗試代碼:

@cast = Cart.where("user_id = ? AND cart_slot_one = nil AND cart_slot_two = nil AND cart_slot_three = nil AND cart_slot_four = ? AND cart_slot_five = ? AND cart_slot_six = ? AND cart_slot_seven = ? AND cart_slot_eight = ? AND cart_slot_nine = ? AND cart_slot_ten = ?", 
    current_user.id, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil).first 
+0

這裏有幾個想法: 你會發現一個所有空購物車或什麼都沒有。如果有幾個,你就隨機選一個(第一個)。這是打算? 你有你的購物車參考(?)插槽?這是你想要的嗎?它不應該是相反的嗎?插槽屬於購物車。然後,您可以根據需要安裝儘可能多的插槽? 你可以展示這裏涉及的模型來澄清這一點嗎? –

+0

你已經在一篇文章中提出了很多問題。首先,你的代碼是否按預期工作?如果不是,那麼實際產出是多少?預期產出是多少? – Agis

+0

@StormViper你問題中的代碼使用'where'的版本,它有一個作爲參數提供的SQL字符串。這與你可以在@ akz92答案中看到的散列參數版本形成對比。當你使用SQL字符串版本時,你需要使用'IS NULL'而不是'= nil'。無論這個語法問題如何,您都應該閱讀關於關聯的內容,以便您不必爲每個「購物車位置」製作命名列。 –

回答

0
@cast = Cart.where(user: current_user, cart_slot_one: nil, cart_slot_two: nil, cart_slot_three: nil, cart_slot_four: nil, cart_slot_five: nil, cart_slot_six: nil, cart_slot_seven: nil, cart_slot_eight: nil) 
@cast.each do |c| 
    c.update_attributes(cart_slot_one: foo') #update all the attributes you want here 
end 
2

要找到一個卡,其中包括所有插槽均爲空

slots = %w(one two three four five six seven eight nine ten) 
query = Hash[slots.map { |slot| ["cart_slot_#{slot}", nil] }] 

@cart = Cart.where(query).find_by(user: current_user) 

或者,如果您的用戶有關聯購物車:

@cart = current_user.slots.find_by(query) 

要找到至少一個空槽一個購物車:

slots = %w(one two three four five six seven eight nine ten) 
query = slots.map { |slot| "cart_slot_#{slot} IS NULL"] }.join(' OR ') 

@cart = Cart.where(query).find_by(user: current_user) 

一旦你找到了這樣的車用以下行來計算或確定空槽:

# count slots: 
count = slots.count { |slot| @cart.send("cart_slot_#{slot}").nil? } 

# get first empty slot: 
slot_number = slots.find { |slot| @cart.send("cart_slot_#{slot}").nil? } 
0
  1. 代替.where(...).first你可以使用.find_by(...) 它基本上是相同的,但是隱含地返回第一個元素或者無
  2. Consid呃使用組合而不是硬編碼插槽。你可以有一個類CartSlot,並在Cart has_many:cart_slots。 而不是檢查每個是空的,你可以檢查是否有任何。
  3. 爲了提高您的解決方案:

    class Cart 
        def self.find_first_empty_for_user(current_user_id) 
        find_by(user_id: current_user_id, cart_slot_one: nil, cart_slot_two: nil, cart_slot_three: nil, cart_slot_four: nil, cart_slot_five: nil, cart_slot_six: nil, cart_slot_seven:nil, cart_slot_eight: nil, cart_slot_nine: nil, cart_slot_ten: nil) 
        end 
    end 
    
    def process(current_user, new_value = 'Whatever) 
        cart = Cart.find_first_empty_for_user(current_user.try(:id)) 
        return unless empty_cart 
        cart.cart_slot_one = new_value 
        cart.save! 
        cart 
    end