在Rails 3中应用此类方法后如何添加备用Flash消息?

时间:2013-04-06 18:26:45

标签: ruby-on-rails ruby ruby-on-rails-3

这是我添加到Rails 3代码

中的模型中的类方法
class Micropost < ActiveRecord::Base

def self.without_review
    where(review: false)
  end

仅供参考,这是显示“评论”的schema.db

 create_table "microposts", :force => true do |t|
    t.text     "content"
    t.boolean  "review",          :default => false
  end

所有帖子默认为review = false,但如果用户在创建之前选中了一个框,则review = true。

这是flash消息

的控制器
  def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = "Posted"
      redirect_to root_path
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

如果review = false,我想要与现在的行为相同,但如果review = true,我想要闪现一条消息,说明“帖子正在审核中”而不是“已发布”

3 个答案:

答案 0 :(得分:0)

只需在create

上进行这些更改即可
  def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save
      if @micropost.review 
        # If review is true. The object @micropost is already built with necessary 
        # parameters sent by the form, say whether review is true.
        flash[:notice] = "Post is under review"
      else
        flash[:success] = "Posted"
        redirect_to root_path
      end
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

答案 1 :(得分:0)

另一种方式是:

  def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = "Posted"
      flash[:success] = "Post is under review" if @micropost.review 
      redirect_to root_path
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

答案 2 :(得分:0)

def create
    @micropost = current_user.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = @micropost.review ? "Posted" : "Post is under review"
      redirect_to root_path
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end