[英]Ruby on rails MYSQL query
I am pretty inexperienced with MySQL queries, but I am currently learning them. 我对MySQL查询没有经验,但是我目前正在学习它们。 How would I find all the nil
fields of an object and then populate just one of those fields? 如何找到对象的所有nil
字段,然后仅填充其中一个字段?
For example, I have an inventory - but I want to find all the empty slots to show me how many slots I have left and then find ones that are empty, and then to populate just one of those fields with a string or number. 例如,我有一个清单-但我想找到所有空插槽以显示剩余的插槽,然后找到空插槽,然后只用字符串或数字填充其中一个字段。
How would I do this? 我该怎么做?
This is the code I attempted: 这是我尝试的代码:
@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
To find a card in which all slots are empty : 要查找所有插槽均空的卡:
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)
Or, if your user has an association to carts: 或者,如果您的用户与购物车相关联:
@cart = current_user.slots.find_by(query)
To find a cart with at least one empty slot : 要找到至少有一个空插槽的购物车:
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)
Once you find such a cart use the following lines to count or determine empty slots: 找到这样的购物车后,请使用以下几行计数或确定空插槽:
# 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? }
@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
.where(...).first
you can use .find_by(...)
which is basically the same but implicitly returns the first element or nil 可以使用.find_by(...)
.where(...).first
,它基本上是相同的,但是隐式返回第一个元素或nil To improve your solution: 要改善您的解决方案:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.