Adding a Like Button which doesn't require User Model

206 views Asked by At

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.

2

There are 2 answers

0
thedanotto On BEST ANSWER

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.

0
kdavh On

If you want a very simple system where anyone can upvote an 'image', you can put a simple counter on each image.

For example, assuming you're using a sql flavor database that has a table called images right now, make a migration with a change method something like this:

def change
  add_column :images, :likes, :integer, default: 0
end

Then in your ImagesController or whatever you're calling it, make an action such as

def upvote
  image = Image.find(params[:id]) # in Rails 4, using strong params, this would look a bit different.
  image.update_attributes(likes: image.likes + 1)
  render json: image
end

There is a lot I'm leaving out, but you may get the idea from this that upvoting without users is actually extremely simple. It only gets complicated once you start trying to keep track of who liked what.