Question

I am currently struggling with a has_many :through association in my project. The basics of the association are as follows:

class Course < ActiveRecord::Base
    has_many :contents
    has_many :topics, :through => :contents
end

class Topic < ActiveRecord::Base
    has_many :contents
    has_many :courses, :through => :contents
end

class Content < ActiveRecord::Base
    belongs_to :courses
    belongs_to :topics
end

probably could not be more basic..

So the idea is that a user can create many courses, and also create many topics. Topics are associated with courses via the Content class. Doing it this way means a user could create a number of topics and associate them with a number of courses. Great, saves the user typing out the lot again when course topics overlap. This is all fine and dandy.

However, I want the user to first create a Course and then from there create a number of new topics for that course. Seems logical to me.

My issue is I am struggling to get my head around the best way to do this?

I could scrap the :through association and have a basic topic belongs_to course association as this would do what i want but at the expense of the extra functionality I want.

I am thinking along the lines of a form_for Topic with fields_for content? I can't help thinking this is a common problem with a common answer but cant find the answer on the interweb. Maybe its my wording. Hope this make complete sense to someone....?

Thanks in advance

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top