【问题标题】:Rails has_and_belongs_to_many associationRails has_and_belongs_to_many 关联
【发布时间】:2011-04-14 15:43:51
【问题描述】:

所以我有两个模型:

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 polymorphic model implementation

的后续

【问题讨论】:

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


    【解决方案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) helper

    【讨论】:

    • 如果您要创建新记录,通常应该使用 PUT 请求。我个人会创建一个连接模型并使用:has_many :through =&gt;。这似乎需要更多的工作,但它会更适合 Rails REST 约定。
    • 谢谢。我正在使用rails3,所以我使用了resources :courses do post 'toggle', :on =&gt; :member end,但是它仍然不起作用,控制台说:ActionController::RoutingError (No route matches "/courses/3/toggle"):
    • 现在看起来可以正常工作了。该操作已在控制器中过滤。 :) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多