4

I've got my models setup for a many-to-many relationship:

class Workshop < ActiveRecord::Base
  has_many :workshop_students
  has_many :students, :through => :student_workshops

  accepts_nested_attributes_for :students
end

class Student < ActiveRecord::Base
  has_many :student_workshops
  has_many :workshops, :through => :student_workshops

  accepts_nested_attributes_for :products
end

class StudentWorkshop < ActiveRecord::Base
  belongs_to :student
  belongs_to :workshop
end

As you can see above, a student can have many workshops and workshop can have many students.

I've looked at the following Rails casts: here and here. And most of the online sources I stumble across only show how to do nested forms for creating new objects within the parent form.

I don't want to create a new object. I only want to add an existing object to the parent form. So for example. If I decide to create a new workshop, I'd like to assign existing students to the workshop.

One thing I don't understand is, how do I link students into the workshop form? Second, when the params are passed, what should be in the controller method for update/create?

If anyone can point me to the right direction, I would appreciate it.

3
  • "Nested forms" aren't legal HTML. Commented May 12, 2011 at 16:55
  • I think he means nested objects within a single form. Commented May 12, 2011 at 22:23
  • Thanks for clearing that up. That is what I meant. Commented May 13, 2011 at 3:42

2 Answers 2

5

The easiest thing to do is:

<%= f.collection_select(:student_ids, Student.all, :id, :name, {:include_blank => true}, {:selected => @workshop.student_ids, :multiple => true} )%>

You should not have to do anything in the create action.

Sign up to request clarification or add additional context in comments.

2 Comments

I have learned from experience to avoid HABTM and use HMT (has_many :through => ). This gives you a model with attributes you can add to later. Even if 'later' only occurs 10% of the time, by that 'time' this stuff is embedded deeply and a major pain to change. Better to have a flexible arrangment at the get go. Some folks effectively consider HABTM to be deprecated at this point, i.e. it works but is not optimal.
I wish I could downvote comments. HABTM is not, and will not, be deprecated.
0

Ok, for anyone coming across the same issue in the future. The solution I came up with was in def create. I am able to access a POST attribute called student_ids, which comes in the form of an array

1 Comment

Could you elaborate on what exactly you did to solve this issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.