How to Create Like in Rails
create like table
class CreateLikes < ActiveRecord::Migration
def change
create_table :likes do |t|
t.boolean :like
t.integer :user_id
t.integer :event_id
t.timestamps
end
end
end
def change
create_table :likes do |t|
t.boolean :like
t.integer :user_id
t.integer :event_id
t.timestamps
end
end
end
relationship like model
belongs_to :user
belongs_to :event
validates_uniqueness_of :user, scope: :event
belongs_to :event
validates_uniqueness_of :user, scope: :event
relationship in user or any model like this
has_many :like, dependent: :destroy
def thumbs_up_total
self.like.where(like: true).size
end
def thumbs_down_total
self.like.where(like: false).size
end
self.like.where(like: true).size
end
def thumbs_down_total
self.like.where(like: false).size
end
Controller code in productcontroller , eventcontroller any model you want to use
def like
#used set_event on bottom and top
like = Like.create(like: params[:like], user: current_user, event: @event)
if like.valid?
flash[:success] = "Your selection was successfull"
redirect_to :back
else
flash[:danger] = "You can only like/dislike a event once"
redirect_to :back
end
end
#used set_event on bottom and top
like = Like.create(like: params[:like], user: current_user, event: @event)
if like.valid?
flash[:success] = "Your selection was successfull"
redirect_to :back
else
flash[:danger] = "You can only like/dislike a event once"
redirect_to :back
end
end
view in you write same as ( x is local object you can replace from your object like event , product)
<div class="thumbs">
<%= link_to like_event_path(x, like: true), method: :post do %>
<i class="white glyphicon glyphicon-thumbs-up"> <%= x.thumbs_up_total %></i>
<% end %>     
<%= link_to like_event_path(x, like: false), method: :post do %>
<i class="white glyphicon glyphicon-thumbs-down"> <%= x.thumbs_down_total %></i>
<% end %>
</div>
<%= link_to like_event_path(x, like: true), method: :post do %>
<i class="white glyphicon glyphicon-thumbs-up"> <%= x.thumbs_up_total %></i>
<% end %>     
<%= link_to like_event_path(x, like: false), method: :post do %>
<i class="white glyphicon glyphicon-thumbs-down"> <%= x.thumbs_down_total %></i>
<% end %>
</div>
route
resources :events do
member do
post 'like'
end
member do
post 'like'
end