首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开始使用Rails教程5.7:文章对象未被正确创建

开始使用Rails教程5.7:文章对象未被正确创建
EN

Stack Overflow用户
提问于 2014-06-06 03:28:24
回答 2查看 1.2K关注 0票数 0

Rails: 4.1.2 Ruby: 2.1.2

我正在尝试完成入门教程(started.html),但是第5.7节有问题。当我的标题和文本都应该正确显示时,我得到了一个“未知属性:标题”。我怀疑文章对象没有被正确地创建或保存,但是我还没有找到这个bug。

这是我的articles_controller.rb:

代码语言:javascript
复制
class ArticlesController < ApplicationController
  def new
  end

  def create
    # render plain: params[:article].inspect
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

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


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

  private :article_params
end

我的show.html.erb:

代码语言:javascript
复制
<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>

我的耙路:

代码语言:javascript
复制
       Prefix Verb   URI Pattern                  Controller#Action
     articles GET    /articles(.:format)          articles#index
              POST   /articles(.:format)          articles#create
  new_article GET    /articles/new(.:format)      articles#new
 edit_article GET    /articles/:id/edit(.:format) articles#edit
      article GET    /articles/:id(.:format)      articles#show
              PATCH  /articles/:id(.:format)      articles#update
              PUT    /articles/:id(.:format)      articles#update
              DELETE /articles/:id(.:format)      articles#destroy
welcome_index GET    /welcome/index(.:format)     welcome#index
         root GET    /                            welcome#index

另外,可能感兴趣的是错误页面所报告的参数,它们看上去并不像我预期的那样,但是我知道什么呢?

参数:

代码语言:javascript
复制
{"utf8"=>"✓",
 "authenticity_token"=>"OFbPxhf...2V+e9zu3A=",
 "article"=>{"title"=>"sdf",
 "text"=>"sadfdf"},
 "commit"=>"Save Article"}

有人能解释一下这件事吗?谢谢!!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-06 05:18:17

基于此,从您的评论中,#<Article id: nil, created_at: nil, updated_at: nil>"的问题是,当您创建您的文章模型时,您没有添加标题和文本列。试试这个:

代码语言:javascript
复制
rails g migration add_title_to_articles title:string text:text
rake db:migrate

这应该会为您的文章模型添加一个title属性,您应该会做得很好。

在阅读了指南的5.4部分之后,我怀疑您忘记了generate命令的一部分,并且丢失了这些字段。而不是这样:

代码语言:javascript
复制
rails generate model Article title:string text:text

你可能是这样做的:

代码语言:javascript
复制
rails generate model Article

这只会生成一个:id、:created_at和:updated_at

started.html#creating-the-article-model

票数 0
EN

Stack Overflow用户

发布于 2014-06-06 04:12:10

这应该是

代码语言:javascript
复制
private
def article_params
    params.require(:article).permit(:title, :text)
  end

并删除这一行private :article_params并尝试一次

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24073721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档