2016-03-07 100 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