【问题标题】:articles_controller.rb:26: syntax error, unexpected end-of-input, expecting keyword_endarticles_controller.rb:26:语法错误,意外的输入结束,期待关键字结束
【发布时间】:2017-01-23 06:15:08
【问题描述】:

我对 Ruby on Rails 非常陌生。我正在尝试通过制作简单的博客来阅读指南并学习。尝试访问 localhost 时,标题中出现错误。我确定这是一个简单的解决方法,但我目前无法看到它。谢谢!

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end
  def create
    @article = Article.new(article.params)

    if @article.save
      redirect_to @article
    else
      render 'new'

  end

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

  def index
     @articles = Article.all
  end

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

【问题讨论】:

  • 您在 create 方法中缺少作为 if 的一部分的结尾

标签: ruby-on-rails ruby


【解决方案1】:

缩进

如果您的文本编辑器无法自动缩进代码,请使用另一个!

如果您的文本编辑器可以缩进代码,请使用它;)

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end
  def create
    @article = Article.new(article.params)

    if @article.save
      redirect_to @article
    else
      render 'new'

    end

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

    def index
      @articles = Article.all
    end

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

可以看到def create是最后一个缩进正确的方法定义,所以问题一定出在这里。

参数

您定义了article_params 方法,但调用了article.params。这可能是另一个问题。

私有方法

在private 关键字之后定义的任何方法都是私有的。在你的情况下,不仅仅是article_params,还有show 和index。我猜最后两个应该是公开的(即上面private关键字)。

【讨论】:

  • 私有修复后关于方法的注释。我明白你在那儿说的话,现在说得很有道理。非常感谢!
  • 如果这解决了您的问题,请将您的问题标记为已回答。
【解决方案2】:

在您的 create 操作中添加 end 字词。这必须工作

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end
  def create
    @article = Article.new(article.params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

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

  def index
     @articles = Article.all
  end

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

【讨论】:

  • 加上额外的“end”我得到一个新错误,“undefined method `each' for nil:NilClass”
  • article_params 而不是article.params 我猜
  • 谢谢VAD!这有帮助。对我来说是漫长的一天,讨厌犯错,哈哈。
  • 没问题,很高兴为您提供帮助!
猜你喜欢
  • 2013-09-18
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
相关资源
最近更新 更多