I'll write this from a somewhat general perspective (but using the models you described), because it is not just relevant to the situation you described, but relevant to any time you're creating a new association in a Many-to-Many relationship using has_many :through
.
In rails, here is a simple example to create a new Topic
object, which is associated with a course
:
@course.topics << Topic.new(params[:topic])
The above assumes you have previously already loaded up your Course
object and stored it in @course
. It also assume that the Topic
data is coming from a form, and stored in the parameter map under the :topic
key.
If you examine your log when this portion executes, because you set up your associations correctly, you should see two insert statements: INSERT INTO "topics"...
and INSERT INTO "contents"...
.
There are other ways (some far more roundabout than others) to do this, but I believe this is the most straightforward.
Let me know if that makes sense.