Kunok
Kunok

Reputation: 8759

Vote implementation for posts in Rails 4

I have models User, Post, Vote. Here is my vote model:

class Vote < ActiveRecord::Base
  SCORE_REGEX = /-1|1/
  # Relations
  belongs_to :user
  belongs_to :post
  # Validations
  validates :score,
    allow_nil: true,
    format: {with: SCORE_REGEX }
end

My posts appear on homepage and user profile. My controllers are: static_pages_controller (this is the controller holds home page), users_controller, posts_controller, votes_controller. I have template for post in views/posts/_post.html.erb which looks like this:

 <%= link_to post.id, post %> <br>
 <%= link_to post.user.name, post.user %>
     <%= post.content %>
  posted <%= time_ago_in_words(post.created_at) %> ago. <br>
  <% if post.edited %>
    post has been edited <%= time_ago_in_words(post.updated_at) %> ago.
  <% end %>
  <% if current_user?(post.user) %>
    <%= link_to "delete", post, method: :delete %>,
    <%= link_to "edit", edit_post_path(post)%>
  <% end %>
  <%= render 'shared/vote_form' %>

How do I make a working vote buttons (Like, unlike, dislike, undislike) for these posts?

Upvotes: 1

Views: 23

Answers (1)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

What keeps you from using a gem like acts_as_votable?

About the buttons, a simple link_to will do with method: 'post' and optionally remote: true. Target for the link, can't say without knowing your routes.

Upvotes: 1

Related Questions