我试图在我的 Ruby on Rails 网站上实现一个评论系统。我基本上遵循了这个线程中的这些准则:Micropost's comments on users page (Ruby on Rails)
但是,当我发布评论时,评论不会显示,并且每个评论框的顶部都会显示文本“资产”。这是从哪里来的?
使用代码更新:我正在使用三个模型来尝试使评论正常工作,如上面的链接所示
用户.rb
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :comments
微博.rb
class Micropost < ActiveRecord::Base
attr_accessible :content, :image, :comment_content
belongs_to :user
has_many :comments, dependent: :destroy
validates :user_id, presence: true
validates :content, presence: true
default_scope order: 'microposts.created_at DESC'
def self.from_users_followed_by(user)
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
where("user_id IN (#{followed_user_ids}) OR user_id = :user_id",
user_id: user.id)
end
end
评论.rb
class Comment < ActiveRecord::Base
attr_accessible :comment_content
belongs_to :user
belongs_to :micropost
validates :comment_content, presence: true
validates :user_id, presence: true
validates :micropost_id, presence: true
end
评论控制器
class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
redirect_to(:back)
else
render 'shared/_comment_form'
end
end
end
微柱控制器
class MicropostsController < ApplicationController
before_filter :signed_in_user
before_filter :correct_user, only: :destroy
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Posted"
redirect_to root_path
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_path
end
private
def correct_user
@micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if @micropost.nil?
end
end
用户控制器
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
@comment = Comment.new
end
意见表
<%= form_for([micropost, @comment]) do |f| %>
路线.rb
resources :microposts do
resources :comments
end
微博视图
<li>
<span class="content"><%= simple_format(micropost.content) %></span>
<%= image_tag micropost.image_url(:thumb).to_s %><br>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<%= render 'shared/comment_form', micropost: micropost %>
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %><br>
<% end %>
</li>