Thursday 22 December 2016

How to Create Like as facebook

1.  rails g model like user_id:integer comment_id:integer

2. in like model make relation
    belongs_to :user
    belongs_to  :comment

3. User model : has_many :likes, dependent: :destroy

4. Comment model : has_many :likes, dependent: :destroy

5 rails g controller Likes create unlike

paste code in like controller 

def create
    @comment = Comment.find(params[:comment_id])
  @like = Like.new(user_id: current_user.id, comment_id: @comment.id)
  @like.save
  @post = @comment.post
  redirect_to @post

  end

  def unlike
 
  @comment = Comment.find(params[:comment_id])
  @like = Like.where(user_id: current_user.id, comment_id: @comment.id).first
  @like.destroy
  @post = @comment.post
  redirect_to @post
  end

6 routes.rb

    get '/like', to: "likes#create"

  get '/unlike', to: "likes#unlike"

7 in view  -> posts -> show.html.erb

<% @post.comments.each do |comment| %>
     <p>
      <strong>Commenter:</strong>
      <%= comment.commenter %>
    </p>
    <!-- <a href="/like?comment_id=<%#= comment.id %>">Like(<%#= Like.where(:comment_id => comment.id).count %>)</a> -->
      <% if comment.likes.where(:user_id => current_user.id).present? %>
      <a href="/unlike?comment_id=<%= comment.id %>">UnLike(<%= comment.likes.count %>)</a>
      <% else %>
      <a href="/like?comment_id=<%= comment.id %>">Like(<%= comment.likes.count %>)</a>
      <% end %>
  </div>
  <% end %>
   

No comments:

Post a Comment

Revert last commit or second last and more....

 Git revert commit_id -m 1 this command willl revert last commit  Git revert commit_id -m 2 this command will revert second commit with same...