gpt4 book ai didi

ruby-on-rails - 从 Controller 传递变量以查看

转载 作者:行者123 更新时间:2023-12-04 04:07:16 24 4
gpt4 key购买 nike

我在Rails上做了一个简单的博客。
我有一个帖子模型和一个评论模型。
当您创建评论时,如果评论无效,我想显示该错误。
我该怎么办?
模型发布:

#/models/post.rb 
class Post < ActiveRecord::Base
has_many :comments
validates :title, :content, :presence => true
end
模特评论:
#/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates :name, :comment, :presence => true
end
评论 Controller
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
end
查看评论表格:
/views/comments/_form.html.erb
<%= form_for([@post, @post.comments.build]) do |f| %>
<% if @comment.errors.any? %>
error!
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
/views/posts/show.html.erb
<%= render 'comments/form' %>
如何从 Controller CommentController传递@comment来查看/post/show.html.erb?
提前致谢。

最佳答案

在您的render "posts/show"中放入redirect_to post_path(@post)而不是CommentsController

关于ruby-on-rails - 从 Controller 传递变量以查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8870138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com