2013-01-16 60 views
0

我有一個叫做文章的模型,它有一個字符串字段,允許用戶將他們的文章設置爲草稿。當選擇草稿並且用戶更新帖子時,我希望它返回到文章編輯頁面,就好像用戶選擇了發佈的選項一樣,然後我希望將用戶重定向到文章索引頁面。Rails將更新草稿保存在控制器中?

問題是如果草稿選項被選中,我無法獲得文章更新並重定向回帖子。我以錯誤的方式接近這個嗎?

遷移文件

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

若y歐真要與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) %>