scope for associations - Rails 4 -
i appreciate if someoneone me write scope displaying number of females (women) attending event.
models
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
terminal
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" } ]
how write scope find payments made females under event?
if write below can find first payment made woman:
event.payments.first.user.category_gender.name 2.3.0 :026 > event.payments.first.user.category_gender.name payment load (0.2ms) select "payments".* "payments" "payments"."event_id" = ? order "payments"."id" asc limit 1 [["event_id", 7]] user load (0.1ms) select "users".* "users" "users"."id" = ? limit 1 [["id", 4]] categorygender load (0.1ms) select "category_genders".* "category_genders" "category_genders"."id" = ? limit 1 [["id", 2]] => "female"
i tried below scope display payments made females event, no luck - tried method no luck. , explanation appreciated on write scope , method:
event.rb
scope :females, -> { joins(payment: :category_gender).where('category_genders.name' => "female") } def females self.payments.where('user.category_gender.name = ?', "female") end
error message:
2.3.0 :004 > event.females payment load (1.7ms) select "payments".* "payments" "payments"."event_id" = ? , (user.category_gender.name = 'female') [["event_id", 7]] sqlite3::sqlexception: no such column: user.category_gender.name: select "payments".* "payments" "payments"."event_id" = ? , (user.category_gender.name = 'female') activerecord::statementinvalid: sqlite3::sqlexception: no such column: user.category_gender.name: select "payments".* "payments" "payments"."event_id" = ? , (user.category_gender.name = 'female')
class payment scope :by_females, -> { joins(user: :category_gender).where(category_genders: { name: 'female' }) } end
now easy usage:
event.payments.by_females
Comments
Post a Comment