如何在 ruby on Rails 中通过从 new 和 create 操作中获取数据来在显示页面上显示数据?

问题描述 投票:0回答:1

您好,我正在使用 Rails,并尝试在单击“提交”按钮后获取数据,但在按“提交”按钮后我的数据未保存,请告诉我如何在保存后在 show.html.erb 上显示数据:这里是代码:

articles_controller.erb:

class ArticlesController < ApplicationController



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



  def index
    @articles = Article.all
  end

  def new
    @article=Article.new
  end



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

  private

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

new.html.erb:

<h1>Create new File</h1>

<%= form_with scope: :article, url: articles_path , local: true do |f| %>
  <p>
    <%= f.label :title, "Title" %><br/>
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description, "Description" %><br/>
    <%= f.text_area :description %>
  </p>
  <p><%= f.submit %> </p>
<% end %>

路线.rb:

Rails.application.routes.draw 做

  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  root "articles#index"
  resources :articles, only: [:edit, :update, :show, :destroy, :index, :new]

end

show.html.erb:

<h1>show</h1>
<h3><strong>Title: </strong><%= @article.title %></h3>
<h3><strong>Description: </strong><%= @article.description %></h3>
ruby-on-rails ruby model-view-controller controller fetch
1个回答
0
投票

什么不起作用以及你是如何得出这个结论的?我假设某些页面呈现显示错误。

浏览代码给人的印象是它应该大致符合您的预期,但是:您没有检查创建操作中的

@article.save
是否有效(感谢分享所有代码,顺便说一句,这使得回答更容易)。

您可以调用

@article.save!
(使用“bang”:!),如果它不起作用(适合调试),它将抛出异常,或者检查 save返回值(其 true 或 false):
if @article.save .... 
。稍后是默认情况,如果您使用 Rails 生成器来搭建资源 (
rails g scaffold MyThing name:string
),您应该会看到它在最简单的默认情况下是如何工作的。您稍后可以手动删除脚手架代码或调用
rails d scaffold MyThing
)。

希望有帮助。也许也存在潜在问题,但请务必检查

create, update, save
的返回值,或调用 bang 版本 (
create!, update!, save!
)。另外,您可以使用
new + save
(或者,使用 bang 调试
@article = Article.create(article_params)
),而不是使用
... cle.create!(...

© www.soinside.com 2019 - 2024. All rights reserved.