EastsideDev
EastsideDev

Reputation: 6639

Using scope in model to manage views

Rails 3.2.18
Ruby 2.1.5

In my models/event.rb, I have:

has_many :registrants

In my models/registrant.rb, I have:

belongs_to :event   

The registrant model has the following fields in it:

event_id
status  

In my controllers/registrants_controller.rb, I have:

def index
  @events = Event.all

So,then in my views/events/index.html.erb, I can use something like:

<% @events.each do |event| %>
  <% event.registrants.each do |registrant| %>  
    ....        

How do I use scope in my model to limit the event.registrants to only those registrants who have a status of 'active'? I know that there may be other ways to do it, but I am trying to learn how to use scope.

Upvotes: 0

Views: 107

Answers (1)

Sander Garretsen
Sander Garretsen

Reputation: 1723

model:

class Registrant < ActiveRecord::Base
  belongs_to :event
  scope :active, -> { where(status: 'active') }
end

view:

<% @events.each do |event| %>
  <% event.registrants.active.each do |registrant| %>

Upvotes: 3

Related Questions