【发布时间】:2017-10-30 07:52:55
【问题描述】:
我有典型的文章和评论博客格式。是典型的has_many/belongs_to,即Guide的博客类型。
但是,我正在尝试编辑文章中的评论,但我对为此构建正确的表单一无所知。
它也是局部的,这对我来说更复杂。
任何帮助和/或教育我将不胜感激。
评论的模型
class Comment < ApplicationRecord
belongs_to :article
end
文章的模型
class Article < ApplicationRecord
has_many :comments
validates :title, presence: true, length: { minimum: 5}
end
文章的显示页面
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
<h2>Comments</h2>
<%= render @article.comments %>
<h2>Add a comment:</h2>
<%= render 'comments/form' %>
<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>
评论的 _comment.html.erb 页面
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<p>
<%= link_to 'Destroy Comment', [comment.article, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
<p>
<%= link_to 'Edit', edit_article_comment_path(@article, comment) %>
</p>
评论的_form.html
<%= form_for([@article, @comment]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
错误
它来自评论的_form.html.erb页面引用此行:<%= form_for([@article, @comment]) do |f| %>...错误是:First argument in form cannot contain nil or be empty...
文章管理员
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
#render plain: params[:article].inspect
#@article = Article.new(params[:article])
#@article = Article.new(params.require(:article).permit(:title, :text))
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def show
@article = Article.find(params[:id])
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
评论控制器
class CommentsController < ApplicationController
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
redirect_to article_path(@article)
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
【问题讨论】:
-
请在您设置
@article和@comment的位置发布控制器操作。 -
另外,如何渲染部分内容?
-
显示你的评论控制器
-
@Gerry,对这么晚的回复感到遗憾。已发布
Articles和Comments控制器。 -
@Pavan,不知道你的意思是我如何渲染部分......认为它在文章的显示页面中可见?即
<%= render @article.comments %>和<%= render 'comments/form' %>...抱歉回复晚了。
标签: ruby-on-rails