title: How do I limit users to "liking" a post only once in ruby on rails?
body: <p>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. </p>
  
  <p><strong>Likes table:</strong></p>
  
  <pre><code>+----+------------+--------------+-------------------------+-------------------------+---------+
  | 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       |
  +----+------------+--------------+-------------------------+-------------------------+---------+
  </code></pre>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p><strong>Like model:</strong></p>
  
  <pre><code>class Like &lt; ActiveRecord::Base
    belongs_to :likable, :polymorphic =&gt; true
    attr_accessible :likable_id, :likable_type, :user_id
  end
  </code></pre>
  
  <p><strong>Micropost model:</strong></p>
  
  <pre><code>class Micropost &lt; ActiveRecord::Base
      belongs_to :user
      has_many :likes, :as =&gt; :likable
  end
  </code></pre>
  
  <p><strong>Likes controller:</strong></p>
  
  <pre><code>class LikesController &lt; ApplicationController
    def create
      micropost = Micropost.find(params[:micropost])
       like = micropost.likes.build(:user_id =&gt; current_user.id)
       like.save
    end
  end
  </code></pre>
  
  <p><strong>Likes form:</strong></p>
  
  <pre><code>&lt;%= form_tag likes_path, :remote =&gt; true, :class =&gt; "like_micropost" do %&gt;  
     &lt;%= hidden_field_tag :micropost, micropost.id %&gt;
         &lt;%= submit_tag '', :class =&gt; "likeMicropostSubmit"  %&gt; 
  &lt;% end %&gt;
  </code></pre>
  
  <p><strong>I previous tried this with no luck:</strong></p>
  
  <pre><code>class LikesController &lt; ApplicationController
    def create
      micropost = Micropost.find(params[:micropost])
      if micropost.likes.where(:user_id =&gt; current_user.id).nil?
       like = micropost.likes.build(:user_id =&gt; current_user.id)
       like.save
      end
    end
  end
  </code></pre>
  
  <p>Kind regards</p>