Rails has_and_belongs_to_many关联

时间:2011-04-14 15:43:51

标签: ruby-on-rails activerecord has-and-belongs-to-many activeview

所以我有两个型号:

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

我没有courses_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 polymorphic model implementation

的后续跟进

1 个答案:

答案 0 :(得分: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)帮助程序