javascriptruby-on-railsrubyajaxsocial-media-like

Adding a Like Button which doesn't require User Model


I'm trying to add a like button to my rails site so I've looked at the acts_as_votable gem and the Active Record Reputation System gem. However, both of these require a User Model (I think), and I want to make the like button something that anyone can click whether they are signed in or not.

Is there a way to make one of these gems function like that, or will I have to create the voting system from scratch? Also, if I do have to do it from scratch, some guidelines to approaching it would be helpful.


Solution

  • I'd create another model called Like and then create a one to many association between Image and Like.

    rails g resource Like image_id:integer
    

    then update your database by running

    rake db:migrate
    

    then you'll want to create the association.

    # like.rb
    class Like < ActiveRecord::Base
      belongs_to :image
    end
    
    # image.rb
    class Image < ActiveRecord::Base
       has_many :likes
    end
    

    Then when someone clicks on the like button, you'll want to create a new Like with the id of the Image

    I hope this helps.