Basically I have a page that lists 10 most recent microposts. Each post has a like button. When this like button is clicked the likes table in my database is updated.
Likes table:
+----+------------+--------------+-------------------------+-------------------------+---------+
| id | likable_id | likable_type | created_at | updated_at | user_id |
+----+------------+--------------+-------------------------+-------------------------+---------+
| 2 | 5770 | Micropost | 2012-06-09 11:30:55 UTC | 2012-06-09 11:30:55 UTC | 2 |
| 3 | 5770 | Micropost | 2012-06-09 11:42:45 UTC | 2012-06-09 11:42:45 UTC | 2 |
+----+------------+--------------+-------------------------+-------------------------+---------+
A user must only be able to like a micropost once. I can make this possible with some jquery/js by displaying an unlike button that points to a destroy path when ever a micropost is liked.
But is there a way to do this server side too? Like not allow a micropost to be liked more than once by any means necessary? So if I was to go into rails console and try to manually like a micropost I already liked it wouldn’t work because it would see that I had already liked the micropost?
Like model:
class Like < ActiveRecord::Base
belongs_to :likable, :polymorphic => true
attr_accessible :likable_id, :likable_type, :user_id
end
Micropost model:
class Micropost < ActiveRecord::Base
belongs_to :user
has_many :likes, :as => :likable
end
Likes controller:
class LikesController < ApplicationController
def create
micropost = Micropost.find(params[:micropost])
like = micropost.likes.build(:user_id => current_user.id)
like.save
end
end
Likes form:
<%= form_tag likes_path, :remote => true, :class => "like_micropost" do %>
<%= hidden_field_tag :micropost, micropost.id %>
<%= submit_tag '', :class => "likeMicropostSubmit" %>
<% end %>
I previous tried this with no luck:
class LikesController < ApplicationController
def create
micropost = Micropost.find(params[:micropost])
if micropost.likes.where(:user_id => current_user.id).nil?
like = micropost.likes.build(:user_id => current_user.id)
like.save
end
end
end
Kind regards
This way you’ll get validation error on trying to like something more than once.
See docs for it.