3
class Allowedevent < ActiveRecord::Base
    :belongs_to :room
    :belongs_to :event
end

class Room < ActiveRecord::Base
    :has_many :allowedevents
    :has_many :events => :through => allowedevents
end

class Event< ActiveRecord::Base
    :has_many :allowedevents
    :has_many :rooms=> :through => allowedevents
end

I'm having difficulty putting the above relationships into a form or playing around with them in the console.

Questions:

  • Now say I save a room, do I have to explicitly add IDs into the allowedevents table? do I have to do this?

    room = Room.new; room.title = "test"; room.allowedevents = ""...?

    as you can see from above, I am lost as to how to save the actual record.

  • basically I want to ask how to save a room into the database that has many allowedevents using the above relationships. Do I have to loop through the user input and save each one to allowedevents? is there a better way?

  • I got the above from railscasts episode, is there an episode on railscasts that actually puts this in perspective on how to use it in the front end?

Tobi
  • 31
  • 1

1 Answers1

2

The front end could be an edit page for room that lists all the events as a set of check boxes. You could then check off the events this room is allowed be reserved for.

Handling this in the room model is a little trickier. Some people would recommend using accepts_nested_attributes_for, but when users later un-check the boxes it doesn't automatically delete the relationship.

The accepts_nested_attributes_for method has an option for deleting records, but forces you to pass in a separate "_delete" parameter for each record you want to dispose of. This is all good if you want to use javascript to add that virtual "_delete" parameter to the form after someone un-checks the box, but if you don't want to rely on javascript it gets tricky.

Therefore I've made the decision to forgo accepts_nested_attributes_for and just roll my own solution, probably similar to how Ryan Bates solved this problem before accepts_nested_attributes_for existed.

Rather than posting my solution, here's a link to the old RailsCast episode which explains how to handle nested models inside a complex form:

http://railscasts.com/episodes/73-complex-forms-part-1

If anyone else has a novel approach to using accepts_nested_attributes_for with checkboxes in a has_many :through style relationship, I would love to hear it.

twmills
  • 2,985
  • 22
  • 20