Sajax
Sajax

Reputation: 13

How to create a Many-to-One relationship with existing records in Rails

I'm trying to implement something similar to that below. Basic setup is a Schedule model

class Schedule < ActiveRecord::Base
  has_many :events
end

The Event model will then belong_to a Schedule. Events are comprised of a name, datetime, running length and a Room

A Room is chosen from a select list when the event is created, all Rooms are created beforehand through seeding or admin interface. Room will store information like seating count.

I've been trying to find a method implementing this that feels right. Solutions seem to range between habtm or has_many :through but I can't see the need for a join table for this situation. Theoretically, an Event has_one :room but the reverse relationship isn't belongs_to :event as a Room may be used for many events, this also requires the foreign key to be on the rooms table.

I've considered handling this manually in the model using a room_id foreign key in the event, I could then query for the relevant Room. I think this would work since I currently cannot see a requirement for finding all events using a Room.

class Event < ActiveRecord::Base
  belongs_to :schedule

  def room
    Room.find(room_id)
  end
end

Everything I've done so far in Rails has felt 'right', but all the solutions I've come up with here doesn't and I feel like I'm missing something; or maybe I'm just expecting that extra bit of magic. Is there a "Rails" way to do this?

Upvotes: 1

Views: 268

Answers (1)

Rafe
Rafe

Reputation: 3066

Wouldn't Event just have a belongs_to relationship to Room in this case?

class Event < ActiveRecord::Base
  belongs_to :schedule
  belongs_to :room
end

If you think about it from a schema perspective, your "events" table almost certainly has "schedule_id" and "room_id" columns.

The other side of the relationship is that a Room has_many Events.

Upvotes: 4

Related Questions