Event Registration Form

2019-07-12 20:46发布

问题:

newbie here...

I am trying to create an events registration page where anybody can register for an event without logging into the system.

My problem is trying to figure out how to tie the registration info to the specific event. I've created all the associations but can't figure how to tell the db that the person is registering for a specific event.

Here are my associations:

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :event_regs
  has_many :regs, through: :event_regs

class Reg < ActiveRecord::Base
  has_many :event_regs

class Reg < ActiveRecord::Base
  has_many :event_regs

Thanks in advance

回答1:

Newbie here

Welcome!


Here's what you'll need:

#app/models/event.rb
class Event < ActiveRecord::Base
   has_many :registrations
end

#app/models/registration.rb
class Registration < ActiveRecord::Base
   belongs_to :event
end

This will allow you to use the following:

#config/routes.rb
resources :events do #-> url.com/events/:id
   resources :registrations #-> url.com/events/:event_id/registrations/
end

#app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
   def new
      @event = Event.find params[:event_id]
      @registration = @event.registration.new
   end

   def create
      @event = Event.find params[:event_id]
      @registration = @event.registration.new registration_params
   end

   private

   def registration_params
      params.require(:registration).permit(:all, :your, :params)
   end
end

This will create a new registration record in your db, associating it with the Event record you've accessed through the route.

--

From this setup, you'll be able to use the following:

#app/controllers/events_controller.rb
class EventsController < ApplicationController
   def show
      @event = Event.find params[:id]
   end
end

#app/views/events/show.html.erb
<% @event.registrations.each do |registration| %>
   # -> output registration object here
<% end %>

Foreign Keys

In order to understand how this works, you'll be best looking at something called foreign keys...

This is a relational database principle which allows you to associate two or more records in different database tables.

Since Rails is designed to work with relational databases, each association you use will require the use of a "foreign key" in some respect.

In your case, I would recommend using a has_many/belongs_to relationship:

You'll need to make sure you add the event_id column to your registrations database.