2015-06-13 67 views
1

我開始使用Socialization寶石。 因此,創建的用戶模型色器件:社會化喜歡

class User < ActiveRecord::Base 
    has_many :posts 
    devise :database_authenticatable, 
    :registerable, 
    :recoverable, 
    :rememberable, 
    :trackable, 
    :validatable 

    acts_as_follower 
    acts_as_followable 
    acts_as_liker 
end 

然後創建後與支架:

class Post < ActiveRecord::Base 
    belongs_to :user 
    acts_as_likeable 
end 

我想允許用戶像帖子。但我不知道如何用像按鈕創建視圖,也不知道如何爲喜歡編寫方法。請舉個小例子。我是新的導軌

我在veiw/posts/show.html.erb中創建鏈接。

<%= link_to "Like", like_post_path(@post), 
:method => :post, :class => 'btn btn-primary btn-xs' %> 

而且在app_contoller方法:

def like   
    @post = Post.find(params[:id]) 
    current_user.like!(@post)  
end 

如何寫路線呢?

回答

1

您可以在您的控制檯已經測試,看看它是如何工作的第一:在你的帖子控制器likesrails c

user = User.first 
post = Post.first 
user.like!(post) 
user.likes?(post) 

所以,你可以創建一個動作。

def likes 
    @user = current_user # before_action :authenticate_user, only: [:likes] 
    @post = Post.find(params[:id]) 
    @user.like!(@post) 
    redirect_to :back, notice: "Liked this post successfully!" 
end 

,並創建該行動路線:

get 'post/:id/likes', to: 'posts#likes', as: :likes 

而在你的觀點:

<%= link_to 'like', likes_path(@post) %> 
+0

謝謝。這是作品! –