Rails: How to use scope to find an element in arra

2019-02-28 17:14发布

问题:

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.

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.

回答1:

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