[英]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: 在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
I don't have a courses_users model, just a join table(courses_users). 我没有courses_users模型,只有联接表(courses_users)。 I guess I'll have to follow/unfollow a course in CoursesController.
我想我必须遵循/取消遵循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: 我在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
这是相关问题Rails多态模型实现的后续活动
THe routing system invokes CoursesController#follow
? 路由系统调用
CoursesController#follow
吗? If not you have to write in the routes.rb
file the following line: 如果不是,则必须在
routes.rb
文件中写以下行:
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 之后,路由系统可以重定向到该操作,它将为您提供
follow_course_url(@course)
帮助程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.