From 461f2de637fed33d2fb4fa442a52f099c786d555 Mon Sep 17 00:00:00 2001 From: Rei Date: Tue, 4 Feb 2014 16:36:09 +0800 Subject: [PATCH] Extract Likeable concern --- app/models/comment.rb | 2 +- app/models/concerns/likeable.rb | 11 +++++++++++ app/models/topic.rb | 2 +- app/views/comments/update.js.erb | 2 +- app/views/topics/show.html.slim | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 app/models/concerns/likeable.rb diff --git a/app/models/comment.rb b/app/models/comment.rb index 9c58bcc..38affe1 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -1,10 +1,10 @@ class Comment < ActiveRecord::Base + include Likeable include Trashable include MarkdownHelper belongs_to :user belongs_to :commentable, polymorphic: true - has_many :likes, as: 'likeable' validates :commentable_type, inclusion: { in: %w(Topic) } validates :commentable, :user, presence: true diff --git a/app/models/concerns/likeable.rb b/app/models/concerns/likeable.rb new file mode 100644 index 0000000..b6f2ff1 --- /dev/null +++ b/app/models/concerns/likeable.rb @@ -0,0 +1,11 @@ +module Likeable + extend ActiveSupport::Concern + + included do + has_many :likes, as: 'likeable', dependent: :delete_all + end + + def liked_by?(user) + likes.where(user: user).exists? + end +end diff --git a/app/models/topic.rb b/app/models/topic.rb index 5b6b78f..b413dc3 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -1,9 +1,9 @@ class Topic < ActiveRecord::Base + include Likeable include Trashable belongs_to :user has_many :comments, as: 'commentable' - has_many :likes, as: 'likeable' def calculate_hot order = Math.log10([comments_count, 1].max) diff --git a/app/views/comments/update.js.erb b/app/views/comments/update.js.erb index 237593f..8562b9c 100644 --- a/app/views/comments/update.js.erb +++ b/app/views/comments/update.js.erb @@ -1,6 +1,6 @@ <% if @comment.errors.empty? %> $('#comment-<%= @comment.id %>').replaceWith('<%= j render @comment %>'); - <% if current_user.likes.where(likeable: @comment).exists? %> + <% if @comment.liked_by?(current_user) %> campo.Likes.updateLike('comment', <%= @comment.id %>); <% end %> <% end %> diff --git a/app/views/topics/show.html.slim b/app/views/topics/show.html.slim index c8ba91b..dfe3764 100644 --- a/app/views/topics/show.html.slim +++ b/app/views/topics/show.html.slim @@ -47,7 +47,7 @@ = f.submit 'Add this comment', class: 'btn btn-success' - if login? - - if current_user.likes.where(likeable: @topic).exists? + - if @topic.liked_by?(current_user) javascript: campo.Likes.updateLike('topic', #{@topic.id});