ActiveRecord Scope

Here are my ActiveRecord models, with Rails 3.2:

class User < ActiveRecord::Base
    has_one :criterion
    has_many :user_offer_choices
end

class Offer < ActiveRecord::Base
    has_many :user_offer_choices

    def seen
        user_offer_choices.where(seen: true)
    end

    def accepted
        user_offer_choices.where(accepted: true)
    end
end

class Criterion < ActiveRecord::Base
    belongs_to :user
end

class UserOfferChoice < ActiveRecord::Base
    belongs_to :user
    belongs_to :offer
end

I want to get all the criteria of users who saw the offer. Sort of:

Offer.find(11).seen.users.criterions

but I don’t know how to work with it with ActiveRecord

I know I can do something like:

Criterion.joins(user: { user_offer_choices: :offer }).where(user: { user_offer_choices: {accepted: true, offer_id: 11}  } )

But I want to be able to use my areas for proposals (visible and accepted). So how can I do this?

Edit: I found what I was looking for, Arel merge method: http://benhoskin.gs/2012/07/04/arel-merge-a-hidden-gem

+5
source share
1 answer

First, what you really want is to identify the area for your options.

class UserOfferChoice < ActiveRecord::Base
  belongs_to :user
  belongs_to :offer

  scope :seen, where(seen: true)
  scope :accepted, where(accepted: true)
end

What allows you to do this

Offer.find(11).user_offer_choices.seen

and get the criteria:

Offer.find(1).user_offer_choices.seen.map{|choice| choice.user}.map{|user| user.criterion}

.

class Offer < ActiveRecord::Base
  has_many :user_offer_choices
  has_many :users, :through => :user_offer_choices
end

, .

Offer.find(1).users

Rails 3, Rails 2.3.5 named_scopes. _scopes , . Rails 3 , , , . , , , !

class User < ActiveRecord::Base
  has_one :criterion
  has_many :user_offer_choices
  has_many :offers, :through => :user_offer_choices

  scope :seen, UserOfferChoice.seen
  scope :accepted, UserOfferChoice.accepted
end

:

Offer.find(1).users.seen

:

Offer.find(1).users.seen.map{|user| user.criterion}

, . , , . , , Rails :

config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural /^criterion$/i, 'criteria'
end
+3

All Articles