Rails在控制器中保存草稿更新?

时间:2013-01-16 06:09:09

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

我有一个名为articles的模型,它有一个字符串字段,允许用户将他们的文章设置为草稿。当选择草稿并且用户更新帖子时,我希望它返回到文章编辑页面,就好像用户选择了已发布的选项,然后我希望将用户重定向到文章索引页面。

问题是,如果选择草稿选项,我无法更新文章并重定向回帖子。我是以错误的方式接近这个吗?

迁移文件

def change
    add_column :articles, :status, :string, default: 'Draft'
  end

articles.rb

scope :submitted, lambda { where('status = ?', 2) }
scope :draft, lambda{ where('status = ?', 1) } 

def is_draft?
  self.draft
end

文章控制器

  def update
      case @article.status
        when 1 
          @article.status = 'Draft'
        else 2 
          @article.status = 'Published'
      end

      if @article.status == 1 
        @article = article.find(params[:id])
        flash[:notice] = "Successfully Updated" if @article.update_attributes(params[:article])
        respond_with(@article, :location => edit_article_path)
      else
        @article = article.find(params[:id])
        flash[:notice] = "Successfully Updated" if @article.update_attributes(params[:article])
        respond_with(@article, :location => articles_path)
      end
  end

1 个答案:

答案 0 :(得分:1)

如果你真的想使用1/2值

型号:

STATUS_VALUES = {1 => "Draft", 2 => "Published"}

scope :submitted, lambda { where('status = ?', STATUS_VALUES[2]) }
scope :draft, lambda{ where('status = ?', STATUS_VALUES[1]) } 

attr_accessible :_status

after_initialize do
  self.draft! if self.new_record?  # be draft by default
end

def draft!
  self.status = STATUS_VALUES[1]
end

def published!
  self.status = STATUS_VALUES[2]
end

def _status
  STATUS_VALUES.invert(status)
end

def _status=(value)
  case value
  when 1, "1" then self.draft!
  when 2, "2" then self.published!
  else self.draft!
  end
end

def draft?
  self.status == STATUS_VALUES[1]
end

def published?
  self.status == STATUS_VALUES[2]
end

控制器:

def update
  @article = article.find(params[:id])
  if @article.update_attributes(params[:article])
    flash[:notice] = "Successfully Updated" 
    if @article.draft?
      respond_with(@article, :location => edit_article_path)
    else
      respond_with(@article, :location => articles_path)
    end
  else
    render :action => :edit
  end
end

查看:

<%= f.check_box(:_status, "Published", 2, 1) %>