[英]Ruby on Rails: How would i stay on the same page if the post is not saved?
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
如果帖子沒有保存,那么它會重定向到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
新方法
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
<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 %>
我該怎么辦 ?
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
,同時應用於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
然后你的new
方法幾乎是空白的並且調用render :new
create
方法中的render :new
應該可以工作。
嘿,這個答案已經很晚了,但我想我會把它添加到遇到它的任何人身上。 對於您想要實現的目標,最簡單的解決方案可能是為所有要填寫的表單輸入添加required:true。 例如
f.text_field :title, required: true, class: "whateverclassyouwant"
這樣,只有在正確填寫這些字段的情況下才會提交表單,如果沒有,則會在需要完成的字段上彈出錯誤的flash消息。 彈出的默認Flash消息也可以自定義樣式,Google如何這樣做。
這樣你就可以在你的create方法中一起刪除else重定向,因為它永遠不會到達那一點,只有if保存,flash成功等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.