acts_as_follower用于多个模型

时间:2013-11-20 22:46:01

标签: ruby-on-rails ruby-on-rails-3

我正在使用acts_as_follower gem。使用示例代码,它对于跟随另一个User对象的用户工作正常。但我也想让用户关注文章。

代码看起来相当简单,只是 FollowsController 似乎是专门针对用户对象编码的。我是否应该为每种类型的对象创建单独的操作?

控制器/ follows_controller.rb

class FollowsController < ApplicationController
  def create
    @user = User.find(params[:user_id])
    current_user.follow(@user)
  end

  def destroy
    @user = User.find(params[:user_id])
    current_user.stop_following(@user)
  end
end

模型/ user.rb

...
acts_as_followable
acts_as_follower
...

模型/ article.rb

class Article < ActiveRecord::Base
  ...
  acts_as_followable
  ...
end

视图/如下/ create.js.erb

$('#follow_user').html('<%= escape_javascript(render :partial => "shared/follow_user", :locals => {:user => @user}) %>');

视图/用户/ show.html.erb

 ...
 <% if user_signed_in? %>
   <div id="follow_user">
     <%= render :partial => "shared/follow_user", :locals => {:user => @user} %>
   </div>
 <% end %>

视图/物品/ index.html.erb

...
<% if current_user.following?(article) %>
    <%= button_to("Un-Follow #{article.id}", article_follow_path(article.to_param, current_user.get_follow(article).id), :method => :delete, :remote => true) %>
<% else %>
    <%= button_to("Follow #{article.id}", article_follows_path(article.to_param), :remote => true) %>
<% end %>

配置/ routes.rb中

resources :articles do
  resources :follows, :only => [:create, :destroy]
end

resources :users do
  resources :follows, :only => [:create, :destroy]
end

1 个答案:

答案 0 :(得分:1)

FollowsController是你的问题。有几种方法可以解决这个问题,其中一种方法是为每个模型使用一个专用的跟随控制器作为一个跟随(例如FollowsUsersController,FollowsArticlesController等)并在config / routes.rb中使用适当的控制器。控制器都可以从一个只留下followable的父FollowsController下载,作为要实现的方法。

在app / controllers / follows_controller.rb

class FollowsController < ApplicationController
  def create
    current_user.follow(followable)
  end

  def destroy
    current_user.stop_following(followable)
  end
end

在app / controllers / follows_users_controller.rb

class FollowsUsersController < FollowsController
  def followable
    @followable ||= User.find(params[:user_id])
  end
end

在app / controllers / follows_articles_controller.rb

class FollowsArticlesController < FollowsController
  def followable
    @followable ||= Article.find(params[:article_id])
  end
end

在config / routes.rb

resources :articles do
  resources :follows, :controller => 'follows_articles', :only => [:create, :destroy]
end

resources :users do
  resources :follows, :controller => 'follows_users', :only => [:create, :destroy]
end

并且您需要为每个控制器定制JS视图

视图/ follows_users / create.js.erb

$('#follow_user').html('<%= escape_javascript(render :partial => "shared/follow_user", :locals => {:user => @followable}) %>');

视图/ follows_articles / create.js.erb

$('#follow_article').html('<%= escape_javascript(render :partial => "shared/follow_article", :locals => {:article => @followable}) %>');