Socialization likes

565 views Asked by At

I start to use Socialization gem. So, created User model with devise:

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

Then I created Post with scaffold:

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

And I want to allow user like posts. But I don't know how to create view with like button, also I dont know how to write methods for likes. Please give me little example. I'm new in rails

I create link in veiw/posts/show.html.erb.

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

And method in app_contoller:

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

How to write route for this?

1

There are 1 answers

0
Florent Ferry On BEST ANSWER

You can already test in your console to see how it works first: rails c

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

So you can create an action: likes in your Posts controller.

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

And create a route for that action:

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

And in your views:

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