【发布时间】:2018-04-27 22:11:27
【问题描述】:
我正在创建我的第一个 RoR 应用程序 - 一个论坛。我正在尝试将 cmets 添加到论坛,但我遇到了一些错误。我在谷歌上搜索过类似的问题,但似乎都没有解决我的问题。这是我的代码:
评论控制器:
class CommentsController < ApplicationController
def create
@forum = Forum.find(params[:forum_id])
if !@forum.nil?
puts "Forum object is not nil"
end
@comment = @forum.comment.create(comment_params)
redirect_to forum_path
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
论坛控制器是自动生成的,我没有改进去。(使用rails生成脚手架论坛,如果你还想看,请告诉我)
class Comment < ApplicationRecord
belongs_to :forum
end
class Forum < ApplicationRecord
has_many :comments
validates :title, presence: true,
length: {maximum: 50}
validates :body, presence: true
end
下面是show.html.erb 论坛页面
的部分表格<h2>Comments</h2>
<% @forum.comments.each do |comment| %>
<p>
<%= comment.body %>
</p>
<% end %>
<h2>Add a comment</h2>
<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
<%= f.label :body %><br/>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
这是来自 rails 的错误:
undefined method `comment' for #<Forum:0x444d518>
摘录如下:
end
@comment = @forum.comment.create(comment_params) #highlighted
redirect_to forum_path
end
【问题讨论】:
-
1) Rails 3 已经过时了。 2)请格式化您的帖子。
-
我同意 coreward,如果这是一个新应用程序,我建议使用 Rails 5。如果您想要稍旧的版本,请使用最新的 Rails 4。顺便说一句,您的模型类的事实继承自
ApplicationRecord让我相信你正在使用 Rails 5。
标签: ruby-on-rails ruby comments ruby-on-rails-5