【问题标题】:Does not update while pressing update on my articles while editing编辑时按我的文章更新时不更新
【发布时间】:2017-09-16 21:18:03
【问题描述】:

我的问题是,在我编辑文章后它会恢复到原来的样子

这些是我在尝试编辑时所采取的步骤的图片:

编辑前:

编辑后:

按下更新按钮后:

我的代码:

articles_controller:

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end 

  def new
    @article = Article.new 
  end

  def edit 
    @article = Article.find(params[:id])
  end 

  def update
    @article = Article.find(params[:id])
    if @article.save 
      flash[:notice] = "article was updated"
      redirect_to(@article)
    else
      render 'edit'
    end 
  end 

  def create
    @article = Article.new(article_params)
    if @article.update(article_params)
      flash[:notice] = "Article was submitted succsefully"
      redirect_to (@article)
    else
      render 'new'
    end 
  end

  def show
    @article = Article.find(params[:id])
  end 

  private 

  def article_params 
    params.require(:article).permit(:title, :description)
  end

end 

【问题讨论】:

  • 您可以添加您正在使用的表单吗?而且,要格式化您的代码,很难阅读。
  • 我尽力了我真的不知道如何格式化......无论如何我不认为我使用任何形式......你能向我解释你在说什么那么也许我会把它放在问题中如果我明白你在说什么或者如果我有它,谢谢你试图帮助
  • 发送数据的表单,看起来像一个脚手架,views/articles下应该有一个_form.html.erb文件。
  • 不,我没有

标签: ruby-on-rails ruby cloud9-ide


【解决方案1】:

在您的update 操作中:

  def update
    @article = Article.find(params[:id])
    if @article.save 
      flash[:notice] = "article was updated"
      redirect_to(@article)
    else
      render 'edit'
    end 
  end 

您永远不会将article_params 分配给@article。你想做这样的事情:

  def update
    @article = Article.find(params[:id])
    @article.update_attributes article_params
    if @article.save 
      flash[:notice] = "article was updated"
      redirect_to(@article)
    else
      render 'edit'
    end 
  end 

使用assign_attributes 设置属性而不进行保存,以便您可以进行if @article.save 测试。

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2012-12-25
    • 2013-01-16
    相关资源
    最近更新 更多