如何制作"喜欢"评论(回复)?

时间:2014-05-28 11:48:23

标签: ruby-on-rails ruby-on-rails-4

有用户表。并且用户必须标记其他用户的评论,这些评论对他们来说是愉快的。如何制作"喜欢"评论(回复)?

Models.rb

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

Controller.rb

class CommentsController < ApplicationController

  def index
    @comments = Comment.all
    @users = User.all
  end

end

查看

<h1>Listing comments</h1>

<table>
  <thead>
    <tr>
      <th>Text</th>
      <th>User</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @comments.each do |comment| %>
      <% @users.each do |user| %>
      <tr>
        <td><%= comment.text %></td>
        <td><%= comment.user.name %></td>
        <td><%= link_to 'Show', comment %></td>
        <td><%= link_to 'Edit', edit_comment_path(comment) %></td>
        <td><%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
  <% end %>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Comment', new_comment_path %>

1 个答案:

答案 0 :(得分:1)

您可能需要另一个模型 - Like

class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :likes
end
class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :commend
end

控制器:

def like
  Like. find_or_create_by_user_id_and_comment_id(current_user.id, params[:commend_id])
end

像这样的东西。您还需要处理验证等问题。