0

所以我有两个模型:

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

在 User.rb 中,我还有:

  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

我没有 course_users 模型,只有一个连接表(courses_users)。我想我必须关注/取消关注 CoursesController 中的课程。我是否在控制器中创建新操作?

现在,当没有遵循课程时,我在课程/显示页面中有一个关注表格

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

我在 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

但看起来它从未激活过。我是否需要修改路线才能激活操作?如何修改它?还是有更好的方法来做到这一点?我可以用一个链接替换表格吗?提前致谢!这是一个相关问题rails 多态模型实现的后续

4

1 回答 1

1

路由系统调用CoursesController#follow? 如果不是,您必须在routes.rb文件中写入以下行:

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

之后路由系统可以重定向到那个动作,它会给你follow_course_url(@course)帮助

于 2011-04-14T15:55:51.067 回答