【发布时间】:2011-10-23 11:05:22
【问题描述】:
我正在尝试创建一种让用户对我的帖子发表评论的方法。目前,我的主页上显示了所有用户帖子,然后在用户个人资料中只有当前用户的帖子。我想拥有它,以便 cmets 仅出现在用户个人资料中的帖子上。我试图在用户配置文件中添加评论表单,但我得到了一个未定义的方法 `cmets' 用于 nil:NilClass 错误。
我的 cmets_controller 看起来像
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
我在用户配置文件中呈现了部分 (_comment_form.html.erb),看起来像
<h2>Add a comment:</h2>
<%= form_for ([@post, @post.comments.build]) do |f| %>
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的评论模型看起来像
class Comment < ActiveRecord::Base
belongs_to :post
end
我的帖子模型看起来像
class Post < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :content, :presence => true
validates :user_id, :presence => true
validates :user, :presence => true
validates :title, :presence => true
has_many :comments
default_scope :order => 'posts.created_at DESC'
end
我的用户配置文件看起来像 show.html.erb
<table class="profile" summary="Profile information">
<tr>
<td class="main">
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
<% unless @user.posts.empty? %>
<table class="posts" summary="User posts">
<%= render @posts %>
<%= render 'comments/comment_form' %>
</table>
<% end %>
</td>
<td class="sidebar round">
<strong>Name</strong> <%= @user.name %><br />
<strong>URL</strong> <%= link_to user_path(@user), @user %><br />
<strong>Tasks</strong> <%= @user.posts.count %>
</td>
</tr>
</table>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 comments posts