该视图只显示Title:和Text:,但似乎不从数据库中获取数据

时间:2022-12-04 23:20:23

I'm a newbie on RoR. I am following Getting Started with Rails and am stuck at Sec 5.7.

我是RoR的新手。我开始使用Rails,并被卡在5.7秒。

I have this as the articles_controller.rb

我把它作为articles_controller.rb。

 class ArticlesController < ApplicationController
 def new
   # @article=Article.new
    end
def create 
    @article = Article.new(params[:article_params])
    @article.save
    redirect_to @article
    end
def show
    @article = Article.find(params[:id])
    end
private 
def article_params
    params.require(:article).permit(:title, :text)
    end

end

结束

This is my show.html.erb-

这是我show.html.erb -

<p>
 <strong>Title:</strong>
 <%= @article.title %>
 </p>

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

when I run the http://localhost:3000/articles/new the form is displayed, entering some Title and some text I click on submit button, the next page has the url: http://localhost:3000/articles/1 or 2(some id). It displays

当我运行http://localhost:3000/articles/new时,会显示表单,在submit按钮上输入一些标题和一些文本,下一页有url: http://localhost:3000/articles/1或2(一些id)。它显示

Title:
Text:

but no value is displayed to the right. I tried other SO question, but it didn't help.

但是在右边没有显示值。我试过其他的问题,但没有用。

Following some SO thread, I also tried replacing @article = Article.find(params[:id]) by @article = Article.find(params[article_params]) in the show action definition of the controller, but it gives some error--

在执行了一些SO thread之后,我还尝试在控制器的show action定义中将@article = Article.find(params[:id])替换为@article = Article.find(params[article_params]),但它会产生一些错误——

param is missing or the value is empty: article

缺少param或值为空:article

error is around this line

误差在这条线上。

params.require(:article).permit(:title, :text)

params.require(:文章)。许可证(:标题、文本)

3 个解决方案

#1


1  

Uncomment the new action, so take away the #. Also on the create action, change to this: @article = Article.new(article_params)

取消对新动作的注释,因此去掉#。对于create操作,也可以更改为:@article = Article.new(article_params)

#2


2  

Try this:

试试这个:

def new
    @article=Article.new
 end
def create 
    @article = Article.new(article_params)
    @article.save
    redirect_to @article
end

#3


2  

Use @article = Article.new(article_params) instead of @article = Article.new(params[:article_params])

使用@article = Article.new(article_params)代替@article = Article.new(params[:article_params])

#1


1  

Uncomment the new action, so take away the #. Also on the create action, change to this: @article = Article.new(article_params)

取消对新动作的注释,因此去掉#。对于create操作,也可以更改为:@article = Article.new(article_params)

#2


2  

Try this:

试试这个:

def new
    @article=Article.new
 end
def create 
    @article = Article.new(article_params)
    @article.save
    redirect_to @article
end

#3


2  

Use @article = Article.new(article_params) instead of @article = Article.new(params[:article_params])

使用@article = Article.new(article_params)代替@article = Article.new(params[:article_params])