简体   繁体   English

Rails:如何使用范围在数组数组中查找元素

[英]Rails: How to use scope to find an element in array of arrays

I have an array of arrays like [["2","3"], ["3","1"], ["6", "1"]] . 我有一个数组[["2","3"], ["3","1"], ["6", "1"]]组成的数组。 The first element of each sub-array is the user ID and the second one is the number of seats the user reserved for an event. 每个子数组的第一个元素是用户ID,第二个是用户为事件保留的座位数。 I want to allow each user to view his reservations by finding his ID in the array. 我想允许每个用户通过在数组中找到其ID来查看其预订。 Suppose that I have two models: User and Event. 假设我有两个模型:User和Event。 In the User controller, I want to use a scope like @mybooking = Event.mybooking(current_user.id) and the problem is how to write the proper scope in the Event model? 在用户控制器中,我想使用@mybooking = Event.mybooking(current_user.id)之类的范围,问题是如何在事件模型中编写适当的范围? And, if the user is found, I want to use its second element, too. 而且,如果找到了用户,我也想使用其第二个元素。

I tried different solutions but didn't work! 我尝试了其他解决方案,但是没有用! Let me know if you think it's not possible using the scope and if you have another kind of solution. 如果您认为使用示波器是不可能的,并且还有另一种解决方案,请告诉我。

Edit: As I'm still waiting for a solution that works, I should mention that I'm looking for something like this: 编辑:由于我仍在等待有效的解决方案,因此我应该提一下,我正在寻找类似的东西:

scope :mybookings, ->(id){where("reservations.to_enum.map{|n,m| n} ?", id)}

or 要么

scope :mybookings, ->(id) { where("reservations.map(&:first) ?", id) }

These two don't work because of the error I get related to "...." part. 由于与“ ....”部分有关的错误,所以这两个命令不起作用。 And, below solution isn't true because I'm calling the Event's scope from User controller and it's not possible to use reservations in that controller because this variable is for the Event controller. 而且,下面的解决方案是不正确的,因为我从User控制器调用了Event的作用域,并且由于该变量用于Event控制器,因此无法在该控制器中使用reservations

class Event
  scope :mybooking, ->(user_ids) { where(user_id: user_ids) }
end

Now it is possible to do in controller: 现在可以在控制器中执行以下操作:

reservations = [["2","3"], ["3","1"], ["6", "1"]]
Event.mybooking(reservations.map(&:first))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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