如果有人能帮助我写一个显示参加活动的女性(女性)人数的范围,我真的很感激。
模型
user.rb
belongs_to :category_gender
has_many :payments
category_gender.rb
has_many :users
event.rb
belongs_to :user
has_many :payments
payment.rb
belongs_to :user
belongs_to :event
终端
event = Event.find(7)
event_payments = event.payments
2.3.0 :054 > event_payments
[
[0] #<Payment:0x007fea72ac5b70> {
:id => 6,
:email => "richill@gmail.com",
:user_id => 4,
:reference => "SPz_ruZ5om",
:created_at => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:updated_at => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:event_id => 7,
:stripe_customer_id => "cus_9YuZZAniFCZVxn",
:stripe_payment_id => "ch_19GTpnAAe71J3vK0aj1gKryO",
:event_payment_date => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:status => "success"
}
[1] #<Payment:0x007fea72ac5b70> {
:id => 7,
:email => "peter@gmail.com",
:user_id => 5,
:reference => "SPz_mnX4ul",
:created_at => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:updated_at => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:event_id => 7,
:stripe_customer_id => "cus_6FhLLMotYCCYvn",
:stripe_payment_id => "ch_20GTunDDt87J3vK1sp4gPry9",
:event_payment_date => Wed, 16 Nov 2016 13:52:23 UTC +00:00,
:status => "success"
}
]
如何编写范围以查找女性在某项活动中支付的所有款项?
如果我写下面的话,我可以找到女人的第一笔付款:
event.payments.first.user.category_gender.name
2.3.0 :026 > event.payments.first.user.category_gender.name
Payment Load (0.2ms) SELECT "payments".* FROM "payments" WHERE "payments"."event_id" = ? ORDER BY "payments"."id" ASC LIMIT 1 [["event_id", 7]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
CategoryGender Load (0.1ms) SELECT "category_genders".* FROM "category_genders" WHERE "category_genders"."id" = ? LIMIT 1 [["id", 2]]
=> "Female"
我尝试了以下范围来显示女性为某项活动支付的所有款项,但没有运气 - 尝试了一种方法,但没有运气。非常感谢您的帮助和解释,将其作为范围和方法撰写:
event.rb
scope :females, -> { joins(payment: :category_gender).where('category_genders.name' => "Female") }
def females
self.payments.where('user.category_gender.name = ?', "Female")
end
错误消息:
2.3.0 :004 > event.females
Payment Load (1.7ms) SELECT "payments".* FROM "payments" WHERE "payments"."event_id" = ? AND (user.category_gender.name = 'Female') [["event_id", 7]]
SQLite3::SQLException: no such column: user.category_gender.name: SELECT "payments".* FROM "payments" WHERE "payments"."event_id" = ? AND (user.category_gender.name = 'Female')
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: user.category_gender.name: SELECT "payments".* FROM "payments" WHERE "payments"."event_id" = ? AND (user.category_gender.name = 'Female')
答案 0 :(得分:3)
class Payment
scope :by_females, -> { joins(user: :category_gender).where(category_genders: { name: 'Female' }) }
end
现在使用方便:
event.payments.by_females