Ruby on Rails:如果post没有保存,我将如何留在同一页面?

def create @addpost = Post.new params[:data] if @addpost.save flash[:notice] = "Post has been saved successfully." redirect_to posts_path else flash[:notice] = "Post can not be saved, please enter information." end end 

如果post没有保存,那么它会重定向到http://0.0.0.0:3000/posts ,但我需要留在页面上,带有文本输入字段,以便用户可以输入数据。

发布模型

 class Post  true validates :content, :presence => true validates :category_id, :presence => true validates :tags, :presence => true end 

新方法

 def new @arr_select = { 1=>"One",2=>"Two" ,3=>"Three" } @categories_select = Category.all.collect {|c| [ c.category_name, c.id ] } end 

new.html.erb

 

Add post

'posts', :action=>'create' do %> :addtextsize %>
10 , :class => :addtextarea %>

:addtextsize %>

我该怎么办 ?

flash.now with render是你正在寻找的。

 flash.now[:notice] = "Post can not be saved, please enter information." render :new 

而不是

 flash[:notice] = "Post has been saved successfully." redirect_to posts_path 

你可以写

 redirect_to posts_path, :notice => "Post has been saved successfully." 

它会做同样的事情。 它只适用于redirect_to ,而不是渲染!

这样的事情应该做你想要的:

 flash[:notice] = "Post can not be saved, please enter information." render :new 

更新 :您更新了您的问题,因此我必须更新我的答案。 渲染执行此操作的正确方法。 但是,您似乎在new方法中加载了一些类别和其他一些东西。 您的create方法应该可以使用这些相同的实例变量。 最简洁的方法是将它们放入另一个方法中,并将该方法用作before_filter ,同时应用于createnew 。 像这样的东西:

 before_filter :load_stuff, :only => [:create, :new] def load_stuff @arr_select = { 1=>"One",2=>"Two" ,3=>"Three" } @categories_select = Category.all.collect {|c| [ c.category_name, c.id ] } end 

然后你的new方法几乎是空白的并且调用render :new create方法中的render :new应该可以工作。

嘿,这个答案是超级迟到的,但我想我会把它添加到碰到它的任何人身上。 对于您想要实现的目标,最简单的解决方案可能是为所有要填写的表单输入添加required:true。 例如

 f.text_field :title, required: true, class: "whateverclassyouwant" 

这样,只有在正确填写这些字段时才会提交表单,如果没有,则会在需要完成的字段上弹出错误消息。 弹出的默认Flash消息也可以自定义样式,Google如何这样做。

通过这种方式,您可以在create方法中一起删除else重定向,因为它永远不会到达那一点,只有if保存,flash成功等。