Ruby学习——Rails官方文档踩坑(一)

Rails官方文档地址:https://ruby-china.github.io/rails-guides/v4.1/getting_started.html

坑1:NoMethodError in ArticlesController#create

描述:根据官方文档,页面录入完表单信息后,提交保存成功,应该重定向到查询页面,但是报了如下截图错误:


原因:因为routes.rb文件中,articles的路由地址应该为resources :articles,错写成了resource :articles,整个routes.rb文件代码如下:

Rails.application.routes.draw do
  get 'welcome/index'
  root "welcome#index"
  resources :articles
end

坑2:NoMethodError in Articles#show
undefined method `title' for nil:NilClass

描述:重定向查询页面后,查不到实体里的属性信息,报错截图如下:


原因:articles_controller.rb文件中private关键字影响了show方法中article的作用域。
articles_controller.rb错误代码如下:

class ArticlesController < ApplicationController
  def new
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  private  #此处影响了下面show方法
    def article_params
      params.require(:article).permit(:title, :text)
    end

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

更改后articles_controller.rb代码如下:

class ArticlesController < ApplicationController
  def new
  end

  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  def show  #show方法提到private前面去,页面就可以正常加载article的属性
    @article = Article.find(params[:id])
  end

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

end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容