如何在Feed中添加多态注释? [英] How to Add Polymorphic Comments to Feed?

查看:64
本文介绍了如何在Feed中添加多态注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图允许用户直接在其活动供稿上添加和查看评论,而不是必须转到显示页面,这是我通过此railscast剧集所做的事情:

I'm trying to allow users to add and see comments directly on their activities feed, instead of having to go to a show page, which is what I got up to with this railscast episode: http://railscasts.com/episodes/154-polymorphic-association-revised.

我从头开始创建了活动供稿.

I created the activities feed from scratch.

下面是我所做的尝试之一.我将逻辑直接添加到索引操作中:

Below is one of the attempt's I made. I added the logic directly into the index action:

class ActivitiesController < ApplicationController
    def index
      @activities = Activity.order("created_at desc").where(current_user.following_ids)
      @activity = Activity.find(params[:id])
      @commentable = @activity
      @comments = @commentable.comments
      @comment = Comment.new
    end
end

告诉我:ActiveRecord::RecordNotFound in ActivitiesController#index Couldn't find Activity with 'id'=

which tells me: ActiveRecord::RecordNotFound in ActivitiesController#index Couldn't find Activity with 'id'=

我试图直接在活动索引中呈现评论的部分内容:

I attempted to render the comments partials directly in the activities index:

<% @activities.each do |activity| %>
  <%= link_to activity.user.name, activity.user %>
  <%= render "activities/#{activity.trackable_type.underscore}/#{activity.action}", activity: activity %>

  <%= render "comments/comments" %>
  <%= render "comments/form" %>
<% end %>

评论/评论& 评论/表格

<% @comments.each do |comment| %>
  <%= User.find(comment.user_id).name %>
  <%= simple_format comment.content %>
<% end %>

<%= form_for [@commentable, @comment] do |f| %>
  <%= f.text_area :content, rows: 4, class: 'form-control', placeholder: 'Enter Comment' %>
  <%= button_tag(type: 'submit', class: "btn") do %>
    <span class="glyphicon glyphicon-plus"></span> Comment
  <% end %>
<% end %>

activity.rb

class Activity < ActiveRecord::Base
  belongs_to :user
  has_many :comments, as: :commentable
  belongs_to :trackable, polymorphic: true
end

感谢您的专业知识!

comments_controller.rb

class CommentsController < ApplicationController
    before_action :load_commentable
  before_action :set_comment, only: [:show, :edit, :update, :destroy, :like]
  before_action :logged_in_user, only: [:create, :destroy]

    def index
        @comments = @commentable.comments
    end

    def new
        @comment = @commentable.comments.new
    end

    def create
        @comment = @commentable.comments.new(comment_params)
        if @comment.save
            redirect_to @commentable, notice: "comment created."
        else
            render :new
        end
    end

    def edit
        @comment = current_user.comments.find(params[:id])
    end

    def update
        @comment = current_user.comments.find(params[:id])
        if @comment.update_attributes(comment_params)
            redirect_to @commentable, notice: "Comment was updated."
        else
            render :edit
        end
    end

    def destroy
        @comment = current_user.comments.find(params[:id])
        @comment.destroy
        redirect_to @commentable, notice: "comment destroyed."
    end

  def like
    @comment = Comment.find(params[:id])
    @comment_like = current_user.comment_likes.build(comment: @comment)
    if @comment_like.save
            @comment.increment!(:likes)
        flash[:success] = 'Thanks for liking!'
    else
        flash[:error] = 'Two many likes'
      end  
        redirect_to(:back)
  end

private
  def set_comment
    @comment = Comment.find(params[:id])
  end

    def load_commentable
        resource, id = request.path.split('/')[1, 2]
        @commentable = resource.singularize.classify.constantize.find(id)
    end

    def comment_params
        params[:comment][:user_id] = current_user.id
        params.require(:comment).permit(:content, :commentable, :user_id, :like)
    end
end

模式

create_table "activities", force: true do |t|
  t.integer  "user_id"
  t.string   "action"
  t.integer  "trackable_id"
  t.string   "trackable_type"
  t.datetime "created_at",     null: false
  t.datetime "updated_at",     null: false
end

add_index "activities", ["trackable_id"], name: "index_activities_on_trackable_id"
add_index "activities", ["user_id"], name: "index_activities_on_user_id"

                   activities GET    /activities(.:format)                                        activities#index
                              POST   /activities(.:format)                                        activities#create
                 new_activity GET    /activities/new(.:format)                                    activities#new
                edit_activity GET    /activities/:id/edit(.:format)                               activities#edit
                     activity GET    /activities/:id(.:format)                                    activities#show
                              PATCH  /activities/:id(.:format)                                    activities#update
                              PUT    /activities/:id(.:format)                                    activities#update
                              DELETE /activities/:id(.:format)                                    activities#destroy

推荐答案

您可以执行以下操作:

# activites/index.html.erb
<% @activities.each do |activity| %>
  # etc.

  <%= render "comments/comments", comments: activity.comments %>
  <%= render "comments/form" %>
<% end %>

# comments/_comments.html.erb
<% comments.each do |comment| %>
  # your code to display each comment
<% end %>

您可以看到我向render方法传递了一个参数:

You can see that I passed an argument to the render method:

render "comments/comments", comments: activity.comments

它将给_comments部分局部变量comments,它等于activity.comments.

It will give to the _comments partial the local variable comments which will be equal to activity.comments.

您甚至可以使用form部分执行几乎相同的操作:

You can even do the almost-same-thing with the form partial:

# activites/index.html.erb
<%= render "comments/form", new_comment: Comment.new(commentable_id: activity.id, commentable_type: activity.class.model_name) %>

# comments/_form.html.erb
<% form_for new_comment do |f| %>


此外,Ruby on Rails中的一个好习惯是不要创建多个实例变量@like_this_one.将其保持在最低限度,因为它可能会造成混淆.我还要补充一点,您的变量命名也很重要.


Also, a good practice in Ruby on Rails is to not create several instance variables @like_this_one. Keep it to the minimum because it can be confusing. I will add that your variable naming is important too.

以下内容:

@activity = Activity.find(params[:id])
@commentable = @activity
@comments = @commentable.comments

可以重构为:

@activity = Activity.find(params[:id])

然后在您的视图中,您可以通过以下方式访问评论:

And then in your views you could access to the comments by doing:

@activity.comments

这篇关于如何在Feed中添加多态注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆