我有典型的文章和评论博客格式。这是典型的has_many / belongs_to,即指南的博客类型。
但是,我正在尝试编辑文章中的评论,而且我对于为此构建正确的表单毫无头绪。
这也是一个让我更复杂的部分。
任何帮助和/或教育我都会受到赞赏。
评论模型
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
答案 0 :(得分:1)
表单中的第一个参数不能包含nil或为空
错误是由于@article
和@comment
在表单中为零。由于您使用局部渲染表单,因此您需要将变量发送到部分
将<%= render 'comments/form' %>
更改为<%= render 'comments/form', article: @article, comment: @comment %>
并且在表单中有<%= form_for([article, comment]) do |f| %>
同样在文章控制器的show
方法中,您应该定义@comment
def show
@article = Article.find(params[:id])
@comment = Comment.new
end