0

so I have two models:

class User < ActiveRecord::Base
  has_and_belongs_to_many :followed_courses,  :class_name => "Course"
end

class Course < ActiveRecord::Base
  has_and_belongs_to_many :followers, :class_name => "User"
end

in User.rb, I also have:

  def following_course?(course)
    followed_courses.include?(course)
  end

  def follow_course!(course)
    followed_courses<<course
  end

  def unfollow_course!(course)
    followed_courses.delete(course)
  end

I don't have a courses_users model, just a join table(courses_users). I guess I'll have to follow/unfollow a course in CoursesController. Do I create a new action in the controller?

Right now, I have a follow form in the courses/show page when the course is not followed

= form_for @course, :url => { :action => "follow" }, :remote => true do |f|
  %div= f.hidden_field :id
  .actions= f.submit "Follow"

And I have in CoursesController:

  def follow
    @course = Course.find(params[:id])
    current_user.follow_course!(@course)
    respond_to do |format|
      format.html { redirect_to @course }
      format.js
    end
  end

But looks like it was never activated. Do I need to modify the route so the action will be activated? How to modify it? Or is there a better way to do this? Can I replace the form with just a link? Thanks in advance! This is a follow-up of a related question rails polymorphic model implementation

Community
  • 1
  • 1
randomor
  • 5,329
  • 4
  • 46
  • 68

1 Answers1

1

THe routing system invokes CoursesController#follow? If not you have to write in the routes.rb file the following line:

map.resources :courses, :member => {:follow => :post} 
#You'll have the map.resources :courses, just add the second argument.

After that the routing system could redirect to that action, and it will you give the follow_course_url(@course) helper

pablorc
  • 940
  • 1
  • 8
  • 20
  • Typically you should be using `PUT` request if you are going to create a new record. Personally I would create a join model and use `:has_many :through =>`. This may seem like more work but it will sit more comfortably with Rails REST conventions. – Paul Sturgess Apr 14 '11 at 15:59
  • thanks. I'm using rails3, so i used `resources :courses do post 'toggle', :on => :member end` however, it still doesn't work, the console says: `ActionController::RoutingError (No route matches "/courses/3/toggle"):` – randomor Apr 14 '11 at 17:10
  • looks like it's working now. The action was filtered in the controller. :) Thanks. – randomor Apr 14 '11 at 17:16