所以我试图学习如何创建一个简单的Ruby on Rails应用程序。我正在创建一个用户可以输入数据的字段。在提交(或创建)时,将保存此数据,然后用户返回主页。所以我有localhost:3000 / listings / new来创建模型,然后我尝试访问localhost:3000 / listings / 1来查看新创建的模型,并遇到Record Not Found错误。我不确定为什么会这样,我已经找了几个小时没有结果。
listings_controller.rb
class ListingsController < ApplicationController
def new
@listing = Listing.new #calls on new method in listing model
end
def create
@listing = Listing.new(listing_params)
@listing.save
redirect_to root_path
end
def show
@listing = Listing.find(params[:id])
end
private
def listing_params
params.require(:listing).permit(:title, :description, :city, :state, :zipcode)
end
end
new.html.erb和show.html.erb(如果需要)
<div class="topbar">
</div>
<div class="container">
<div id="contact-area">
<%= form_for @listing do |f| %>
<!-- taken from schema.rb -->
<%= f.label :title %>
<%= f.text_field :title %> <!-- use text field when body is just 1 line -->
<%= f.label :description %>
<%= f.text_area :description %> <!-- more for paragraphs -->
<%= f.label :city %>
<%= f.text_field :city %>
<%= f.label :state %>
<%= f.text_field :state %>
<%= f.label :zipcode %>
<%= f.text_field :zipcode, class: "zip-width", maxlength: "5" %>
<%= f.submit class: "create-button"%>
<% end %>
</div>
</div>
和
<div class="topbar">
<div class="container">
<div class="vertical-center">
<%= link_to 'home', root_path %> > jobs > accounting
</div>
</div>
</div>
<div class="container">
<div>
<button type="button">reply</button>
posted <%= time_ago_in_words(@listing.created_at) %>
<h1 class="listing-header"><%= @listing.title %></h1>
<div class="box">
<p>test</p>
</div>
<p><%= @listing.description%></p>
</div>
<footer>
<p>post id: <%= @listing.id%></p>
<p>posted <%= time_ago_in_words(@listing.created_at) %></p>
</footer>
</div>
的routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
#NOTE USE rake routes TO SEE ALL ROUTES
#Creates the CRUD actions for categories
resources :categories do
resources :subcategories #Creates CRUD actions for subcategories
end
resources :listings
root 'categories#index' #first page that we land on -- homepage
#matching paths to pages controller
match '/help', to: 'pages#help', via: :get
match '/scams', to: 'pages#scams', via: :get
match '/safety', to: 'pages#safety', via: :get
match '/terms', to: 'pages#terms', via: :get
match '/privacy', to: 'pages#privacy', via: :get
match '/about', to: 'pages#about', via: :get
match '/contact', to: 'pages#contact', via: :get
end
答案 0 :(得分:0)
当您尝试创建列表时,可能会遇到某种类型的验证错误,并且正在回滚创建。要查看有关此内容的信息性错误,请通过替换以下内容更新您的创建操作:
@listing.save
带
@listing.save!
前者(你拥有的)以静默方式失败,只为无效记录返回false。后者(随着爆炸)失败,无效记录例外。
答案 1 :(得分:-1)
将其作为
def create
@listing = Listing.new(listing_params)
if @listing.save
flash[:notice] = "Listing created successfully."
redirect_to listing_path(@listing)
else
flash[:error] = @listing.errors.full_messages
render 'new'
end
end
并检查闪存中的错误消息