Rails: 4.1.2 Ruby: 2.1.2
我正在尝试完成入门教程(started.html),但是第5.7节有问题。当我的标题和文本都应该正确显示时,我得到了一个“未知属性:标题”。我怀疑文章对象没有被正确地创建或保存,但是我还没有找到这个bug。
这是我的articles_controller.rb:
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:
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>我的耙路:
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另外,可能感兴趣的是错误页面所报告的参数,它们看上去并不像我预期的那样,但是我知道什么呢?
参数:
{"utf8"=>"✓",
"authenticity_token"=>"OFbPxhf...2V+e9zu3A=",
"article"=>{"title"=>"sdf",
"text"=>"sadfdf"},
"commit"=>"Save Article"}有人能解释一下这件事吗?谢谢!!
发布于 2014-06-06 05:18:17
基于此,从您的评论中,#<Article id: nil, created_at: nil, updated_at: nil>"的问题是,当您创建您的文章模型时,您没有添加标题和文本列。试试这个:
rails g migration add_title_to_articles title:string text:text
rake db:migrate这应该会为您的文章模型添加一个title属性,您应该会做得很好。
在阅读了指南的5.4部分之后,我怀疑您忘记了generate命令的一部分,并且丢失了这些字段。而不是这样:
rails generate model Article title:string text:text你可能是这样做的:
rails generate model Article这只会生成一个:id、:created_at和:updated_at
started.html#creating-the-article-model
发布于 2014-06-06 04:12:10
这应该是
private
def article_params
params.require(:article).permit(:title, :text)
end并删除这一行private :article_params并尝试一次
https://stackoverflow.com/questions/24073721
复制相似问题