MaruniakS MaruniakS - 7 months ago 43
Ruby Question

Rails 4 scope has_many

I have two models

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

class ProjectType < ActiveRecord::Base
belongs_to :portfolio
end


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

Answer

Add an appropriate scope to your model:

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

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

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)
Comments