简体   繁体   中英

Rails has_and_belongs_to_many association

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM