Topic: Adding a bunch of events to a league via checkboxes

Hi all,

I am building a Fantasy League website -- and I am trying to figure out how I can let the user assign pre-defined events (defined by me as website admin) to his league to create a "league schedule".

I have a League model, with a nested Event model.

But ...

.. this may be wrong to start with, because a random user can create a league, but they can not create events. They can only assign existing events to their league schedule.

The website administrator creates the events via the ActiveAdmin back-end so that league admins can pick the ones they want to use.

The way I set it up now is that a League can have many events and events belong to many leagues. I'm using a join table model called ScheduledEvent.

routes.rb

resources :leagues do
    resources :events
  end

I set it up like this purely for the paths, so that a league's administrator can visit /leagues/1/events to assign events.
Does nesting :events even make sense in this scenario?

league.rb

class League < ActiveRecord::Base
  has_many :scheduled_events
  has_many :events, :through => :scheduled_events
 end

event.rb

class Event < ActiveRecord::Base
  has_many :scheduled_events
  has_many :leagues, :through => :scheduled_events
end

scheduled_event.rb

class ScheduledEvent < ActiveRecord::Base
  belongs_to :league
  belongs_to :event
end

What I want to do is have a page where I list all of the available events as checkboxes so that the league's administrator can add multiple events to the league.

events_controller.rb

class EventsController < ApplicationController
  before_filter :get_league
  before_filter :authenticate_user!

  def index
    @scheduled_events = @league.events 
    @all_events       = Event.future_events  
  end

  ...  

end

The view should look somewhat like this:

#events
  %h1 Events
    = form_for @league, :url => league_events_path(@league), :method => :post do |f|
      - @all_events.each do |event|
        = check_box_tag :event_ids, event.id, @league.events.include?(event), :name => 'league[event_ids][]'
        = label_tag :event_ids, event.name
      = submit_tag

Right now I am using index.html.haml from the Event controller. Again, not confident I am doing it right sad

I stole this code from an article from 2008, so I am sure RoR 3.x has improved and there is a better way of doing this. I also have to be honest - I really feel lost, so I am not even sure what is happening sad

Can someone guide me in some of the issues concerning correct design patterns for this problem?

Last edited by scriptdude (2012-05-11 18:28:44)

Re: Adding a bunch of events to a league via checkboxes

I would checkout this Railscast: http://railscasts.com/episodes/17-habtm … play=true. It is a paid one though. There is an older version of it that is free though.