Ruby on Rails:如果帖子没有保存,我如何保持在同一页面上? [英] Ruby on Rails: How would i stay on the same page if the post is not saved?

查看:30
本文介绍了Ruby on Rails:如果帖子没有保存,我如何保持在同一页面上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ,但我需要留在页面上,带有文本输入字段,以便用户可以输入数据.

If the post is not saved then it redirects to http://0.0.0.0:3000/posts , but i need to stay on the page, with text input fields so that user can input data.

发布模型

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

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 with render is what you're looking for.

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,但不适用于渲染!

and it will do the same thing. It works only with redirect_to though, not with render!

这篇关于Ruby on Rails:如果帖子没有保存,我如何保持在同一页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆