0

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

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

迁移文件

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

文章.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
4

1 回答 1

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) %>
于 2013-01-16T06:33:25.997 回答