【发布时间】:2010-12-04 22:03:11
【问题描述】:
我正在试用用 rails 编写的 beast 论坛,并将以此作为我一直面临的问题的示例。
论坛有一个主题/显示操作和视图,底部有一个表单,用于在主题内创建新帖子。
提交表单进入帖子/创建,如果验证通过重定向回主题/显示并且工作正常,但是如果验证失败(省略正文字段),您将被重定向到相同的主题/显示并返回到表单,没有验证错误...通常如果验证失败,您将留在任何/创建渲染:action => new。
在重定向中是否丢失了验证,让它工作的最佳方法是什么?
见下面的代码:
PostsController.rb
def create
@post = current_user.reply @topic, params[:post][:body]
respond_to do |format|
if @post.new_record?
format.html { redirect_to forum_topic_path(@forum, @topic) }
format.xml { render :xml => @post.errors, :status => :unprocessable_entity }
else
flash[:notice] = 'Post was successfully created.'
format.html { redirect_to(forum_topic_post_path(@forum, @topic, @post, :anchor => dom_id(@post))) }
format.xml { render :xml => @post, :status => :created, :location => forum_topic_post_url(@forum, @topic, @post) }
end
end
end
TopicsController.rb
def show
respond_to do |format|
format.html do
if logged_in?
current_user.seen!
(session[:topics] ||= {})[@topic.id] = Time.now.utc
end
@topic.hit! unless logged_in? && @topic.user_id == current_user.id
@posts = @topic.posts.paginate :page => current_page
@post = Post.new
end
format.xml { render :xml => @topic }
end
end
主题/显示视图
<% form_for :post, :url => forum_topic_posts_path(@forum, @topic, :page => @topic.last_page) do |f| %>
<%= f.error_messages %>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td rowspan="2" width="70%">
<%= f.text_area :body, :rows => 8 %>
</td>
<td valign="top">
<%= render :partial => "posts/formatting" %>
</td>
</tr>
<tr>
<td valign="bottom" style="padding-bottom:15px;">
<%= submit_tag I18n.t('txt.views_topics.save_reply', :default => 'Save reply') %>
</td>
</tr>
</table>
<% end %>
非常感谢。
【问题讨论】:
-
工作流程本身看起来很奇怪
-
你是什么意思?如果没有这个例子,我可能会更简单地问它。基本上,如果你重定向而不是渲染,错误消息会发生什么,在哪里可以访问它们?
-
主要问题是使用重定向而不是渲染。通常人们会在创建/新控制器操作中使用
render 'new'来保留对象和object.errors。使用重定向需要复杂的代码来保持对象数据的活跃。