Rails:如何使用范围在数组数组中查找元素 [英] Rails: How to use scope to find an element in array of arrays

查看:53
本文介绍了Rails:如何使用范围在数组数组中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,如 [["2","3"], ["3","1"], ["6", "1"]].每个子数组的第一个元素是用户 ID,第二个元素是用户为活动保留的座位数.我想允许每个用户通过在数组中查找他的 ID 来查看他的预订.假设我有两个模型:用户和事件.在用户控制器中,我想使用像 @mybooking = Event.mybooking(current_user.id) 这样的范围,问题是如何在事件模型中编写正确的范围?而且,如果找到用户,我也想使用它的第二个元素.

I have an array of arrays like [["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. I want to allow each user to view his reservations by finding his ID in the array. Suppose that I have two models: User and 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? 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.

由于我仍在等待有效的解决方案,我应该提到我正在寻找这样的东西:

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)}

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

这两个不起作用,因为我得到了与...."部分相关的错误.而且,下面的解决方案是不正确的,因为我从用户控制器调用事件的范围,并且不可能在该控制器中使用 reservations,因为该变量用于事件控制器.

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.

推荐答案

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))

这篇关于Rails:如何使用范围在数组数组中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆