有人可以告诉我如何将下面的方法变成一个范围。
@event.current_user_attending_paid?(@user)
我发现这很有挑战性。会是这样的:event.rb文件中的scope :booked_events, -> { joins(:payments).where(payment.user_id: user) }
吗?
event.rb
has_many :payments
#checks if current user has paid to attend event
def current_user_attending_paid?(user)
self.payments.exists?(user: user)
end
payment.rb
class Payment < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
user.rb
has_many :payments
答案 0 :(得分:1)
scope :paid?, -> (user, event) { where(user_id: user.id, event_id: event.id) }
这将返回一个活动记录收集ActiveRecord :: Relation对象
现在在视图中,您可以使用类似Payment.paid?(User.first, Event.first).exists?
exists? returns false if result is empty.
答案 1 :(得分:1)
你几乎可以在尝试中解决这个挑战。在event.rb
scope :booked_events, -> (user) { joins(payments: :user).where(users: { id: user.id }) }