成功完成微博系统后。登录用户可以通过表单发布并创建帖子。我开始添加这个,但允许任何用户也对帖子发表评论。
我遇到了很多错误。在大多数情况下,我不知道问题是什么,所以有人建议如何完成这个。现在错误是:
StaticPages #home中的NameError 未定义的局部变量或方法`micropost'
StaticPages #home是显示每个人微博的页面,因此也会形成评论。用户#show是用户的公开个人资料,显示与statispages相同(尚未确定如何向用户墙发帖),最终主页将是一般提要,用户页面将是用户对用户提要)。
评论模型
create_table "comments", force: true do |t|
t.string "content"
t.integer "user_id"
t.integer "micropost_id"
t.datetime "created_at"
t.datetime "updated_at"
end
User.rb
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :comments
micropost.rb
belongs_to :user
has_many :comments, dependent: :destroy
comment.rb
belongs_to :user
belongs_to :micropost
comments_controller.rb
class CommentsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = Comment.new(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user
if @comment.save
flash[:success] = "Comment created!"
redirect_to current_user
else
render 'shared/_comment_form'
end
end
end
microposts_controller.rb
class MicropostsController < ApplicationController
before_action :authenticate_user!
before_action :correct_user, only: :destroy
def index
@microposts = Micropost.all
@comment = @micropost.comments.build(params[:comment])
@comment.user = current_user
end
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = []
render root_url
end
end
def destroy
@micropost.destroy
redirect_to root_url
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
users_controller.rb
def show
@user = User.find(params[:id])
@microposts = @user.microposts
@comment = Comment.new
if user_signed_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @user }
end
end
任何地方都在调用评论表单
<%= render 'shared/comment_form', micropost: micropost %>
_comment_form.html.erb
<%= form_for([micropost, @comment]) do |f| %> #Here's the current error#
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, :placeholder => "Leave a comment" %>
</div>
<button class="btn" type="submit">
Create
</button>
<% end %>
架构显示模型的所有正确字段。所有数据库迁移都已完成。我已经看到它在form_for([micropost,@ comment])中说第一个字段不能为零。我假设这意味着评论没有正确地填充micropost_id与他们附加的微博的id。