The title might be a little weird but let me explain.
I have User, Course, and Subscription models. User has_many :courses, :through => :subscription and Course has_many :users, :through => :subscription. Subscription belongs_to both. That part, I understand completely. I’m using the subscription model to store the state of the relationship (completed, failed, dropped, active, etc) between user and course.
I also have this code which creates the relationship:
@subscription = Subscription.create!(:course_id => @course.id, :user_id => current_user.id)
As of now, I don’t have a Subscriptions controller since they will be managed mainly through the course views (but I’m not set on one way or another, I just want to do it right).
What I don’t understand is how/where to implement the action of a user subscribing to a course. Should it be a separate action in the Course controller with a route that you link to or is there another, better way to do it? I imagine AJAX would be one way of doing it as well, but I have no idea how to implement that.
I’ve looked through Michael Hartl’s rails tutorial, done some google searching over the past couple days, and even browsed the source code for Diaspora (since the action I’m trying to do is similar to friending someone, though the associations are different), but I can’t seem to wrap my head around it.
Well, I figured out how to do it.
In my subscriptions controller, I made the
createmethod which look like this:After that, I can use the
button_tohelper in my views to create a simple form with one button that points to the create action on my subscriptions controller:<%= button_to "Subscribe!", subscriptions_path(:course_id => @course.id) %>It’s also necessary, of course, to add the appropriate actions to routes.rb:
resources :subscriptions, :only => [:create, :update]It can definitely be cleaned up, but for the time being, it works nicely.