MaruniakS MaruniakS - 2 years ago 158
Ruby Question

Rails 4 scope has_many

I have two models

class Portfolio < ActiveRecord::Base
has_many :project_types, dependent: :destroy

class ProjectType < ActiveRecord::Base
belongs_to :portfolio

ProjectType model has field
. It can be 'web' or 'mobile', etc.
How can I get all 'web' or 'mobile' portfolios using scopes?

Answer Source

Add an appropriate scope to your model:

# in models/project_type.rb
class ProjectType < ActiveRecord::Base
  belongs_to :portfolio

  scope :web, -> { where(ptype: 'web') }

To load portfolios with type web only use that scope with a join in the controller:

# in the controller
@web_portfolios = Portfolio.joins(:project_types).merge(ProjectType.web)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download