2013-11-20 38 views
0

我正在使用acts_as_follower寶石。使用示例代碼,它可以在另一個用戶對象之後正常工作。但我也想讓用戶關注文章。acts_as_follower對於多個模型

該代碼看起來相當簡單,除了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 %> 

config/routes.rb

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

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

回答

1

FollowsController是你的問題。有幾種方法可以處理這個問題,其中之一是爲每個模型使用一個專用的跟隨控制器,作爲一個跟隨(例如FollowsUsersController,FollowsArticlesController等),並在config/routes.rb中使用適當的控制器。這些控制器都可以從父控制器FollowsController中下載,它只是將followable作爲要實現的方法。

在應用程序/控制器/ follows_controller.rb

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

    def destroy 
    current_user.stop_following(followable) 
    end 
end 

在應用程序/控制器/ follows_users_controller.rb

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

在應用程序/控制器/ 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 

,你需要爲每個控制器

的意見/ follows_users/create.js.erb

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

的意見/ follows_articles/create.js定製JS的看法。erb

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

完美答案。非常感謝。 – ardochhigh