【发布时间】:2012-09-17 05:51:16
【问题描述】:
晚上好,
在过去的几个小时里,我一直坐在这里摸不着头脑。
我有一个非常简单的 cmets 模型附加到文章模型。问题是,每篇文章 cmets 部分的末尾似乎都有一个空白评论。如果我尝试使用一种方法,如将其大写,则会出现“在 nil 类上大写”的错误,如果我将 cmets 放入每个评论(facebook 样式)的灰色背景的 div 中,则会在文章末尾出现一个空白框厘米。有谁知道怎么回事?
无论如何,代码如下: 评论控制器
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(params[:comment])
if @comment.save
flash[:success] = "Comment created"
redirect_to @article
else
flash[:error] = "Something went wrong"
redirect_to @article
end
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to @article
end
end
cmets 模型
attr_accessible :name, :content
belongs_to :article
validates_presence_of :article_id
validates_presence_of :content, length: { maximum: 300 }
default_scope order: "comments.created_at DESC"
意见表
<a href='#', id='comments-form', class="btn btn-large">Add a comment</a>
<div id="comment">
<%= form_for([@article, @article.comments.build]) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :content %>
<%= f.text_field :content %>
<br>
<%= f.submit "Create", class: "btn btn-large" %>
<% end %>
</div>
cmets 展示
<legend>Comments</legend>
<% comments.each do |comment| %>
<sabon><%= comment.name %></sabon><br>
<p><%= comment.content %></p>
<hr>
<% end %>
文章底部显示
<%= render partial: "comments/form", locals: { article: @article } %><br><br>
<%= render partial: "comments/show", locals: { comments: @article.comments }%>
路线
resources :articles do
resources :comments
end
任何帮助都会非常感谢大家,提前感谢 Andy,如果您需要更多代码,请大声疾呼。
【问题讨论】:
-
你能查一下数据库,看看是否真的有空白评论吗?或者rails只是写一个?
-
表单中的
@article.comments.build行构建新的评论对象。然后在 show partial 中列出带有此空白注释的 @article.cmets。 -
把它作为一个答案随便和生病的投票和打勾,干杯!!
标签: ruby-on-rails ruby comments associations