shi*_*bly 14 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1
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
Run Code Online (Sandbox Code Playgroud)
如果帖子没有保存,那么它会重定向到http://0.0.0.0:3000/posts,但我需要留在页面上,带有文本输入字段,以便用户可以输入数据.
发布模型
class Post < ActiveRecord::Base
has_many :comments
validates :title, :presence => true
validates :content, :presence => true
validates :category_id, :presence => true
validates :tags, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
新方法
def new
@arr_select = { 1=>"One",2=>"Two" ,3=>"Three" }
@categories_select = Category.all.collect {|c| [ c.category_name, c.id ] }
end
Run Code Online (Sandbox Code Playgroud)
new.html.erb
<h3>Add post</h3>
<%= form_tag :controller=>'posts', :action=>'create' do %>
<%= label :q, :Title %>
<%= text_field :data, :title, :class => :addtextsize %><br/>
<%= label :q, :Content %>
<%= text_area :data, :content, :rows=>10 , :class => :addtextarea %><br/>
<%= label :q, :Category %>
<%= select :data, :category_id, @categories_select %><br/>
<%= label :q, :Tags %>
<%= text_field :data, :tags, :class => :addtextsize %><br/>
<%= label :q, :Submit %>
<%= submit_tag "Add Post" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
我该怎么办 ?
Jak*_*old 17
flash.now同render是你在找什么.
flash.now[:notice] = "Post can not be saved, please enter information."
render :new
Run Code Online (Sandbox Code Playgroud)
而不是
flash[:notice] = "Post has been saved successfully."
redirect_to posts_path
Run Code Online (Sandbox Code Playgroud)
你可以写
redirect_to posts_path, :notice => "Post has been saved successfully."
Run Code Online (Sandbox Code Playgroud)
它会做同样的事情.它只适用于redirect_to,而不是渲染!
这样的事情应该做你想要的:
flash[:notice] = "Post can not be saved, please enter information."
render :new
Run Code Online (Sandbox Code Playgroud)
更新:您更新了您的问题,所以我必须更新我的答案.渲染是执行此操作的正确方法.但是,看起来您在new方法中加载了一些类别和其他一些东西.您的create方法应该可以使用这些相同的实例变量.要做到这一点,最彻底的方法是把它们变成另一种方法,并有用作方法before_filter应用到create和new.像这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
然后你的new方法几乎是空白的,并且调用render :new你的create方法应该可行.