我對 Rails 和一般的全堆疊開發非常陌生。我剛剛完成了 Michael Hartl 的 Ruby on Rails 教程第 6 版,并且正在再次通過它來構建我的第一個專案(即一個不同于書中構建的示例應用程式的應用程式,但借鑒了許多相同的課程)。關鍵是新專案正在使用 Rails 7。
在我遇到第 7 章的問題之前,一切都很順利;對于向新用戶表單提交的錯誤訊息,我的應用程式不會呈現部分錯誤訊息。部分代碼執行(通過除錯器驗證,稍后使用 puts 陳述句在控制臺上輸出),但不輸出 HTML(即在 Chrome 中檢查頁面時找不到它)。有一個與較新版本的引導程式相關的 CSS 問題,但我什至嘗試從本書(3.4.1)降級到引導程式版本,但沒有運氣。(有問題的 CSS 部分在下面注釋掉)
我已經為此努力了幾個小時。希望這只是我想念的愚蠢的東西。如果這是 Bootstrap 與 Importmaps 的更廣泛的問題,或者我也希望在學習這些的好地方提供參考。我非常感謝任何想法!
編輯這絕對不是將區域變數傳遞給區域變數的問題;請參閱本文末尾添加的代碼片段和評論。
app/views/users/new.html.erb:
<% provide(:title, 'Create New User') %>
<h1>Create New User</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: @user, local: true) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :email %>* <i>required</i>
<%= f.email_field :email %>
<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%= f.label :last_name %>
<%= f.text_field :last_name %>
<%= f.label :phone_number %>
<%= f.text_field :phone_number %>
<% # f.label :admin, "Company Admin" %>
<% # f.radio_button :admin, "True" %>
<% # f.label :admin, "Regular User" %>
<% # f.radio_button :admin, "False", :checked => true %>
<%= f.submit "Create New User", class: "btn btn-primary" %>
<% end %>
</div>
</div>
app/views/shared/_error_messages.html.erb:
<% if @user.errors.any? %>
<% puts "the error partial was called" %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(@user.errors.count, "error") %>
</div>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
提交應生成錯誤的錯誤資料(電子郵件驗證失敗)時的示例服務器輸出:
Started POST "/users" for 24.85.170.222 at 2022-02-14 01:01:56 0000
Cannot render console from 24.85.170.222! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by UsersController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"no123@good-email", "first_name"=>"Jeff", "last_name"=>"Lebowski", "phone_number"=>""}, "commit"=>"Create New User"}
(0.1ms) SELECT sqlite_version(*)
? app/controllers/users_controller.rb:13:in `create'
TRANSACTION (0.1ms) begin transaction
? app/controllers/users_controller.rb:13:in `create'
User Exists? (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "no123@good-email"], ["LIMIT", 1]]
? app/controllers/users_controller.rb:13:in `create'
TRANSACTION (0.1ms) rollback transaction
? app/controllers/users_controller.rb:13:in `create'
Rendering layout layouts/application.html.erb
Rendering users/new.html.erb within layouts/application
the error partial was called
Rendered shared/_error_messages.html.erb (Duration: 1.8ms | Allocations: 701)
Rendered users/new.html.erb within layouts/application (Duration: 6.2ms | Allocations: 2949)
Rendered layouts/_rails_default.html.erb (Duration: 6.7ms | Allocations: 6277)
Rendered layouts/_shim.html.erb (Duration: 0.5ms | Allocations: 153)
Rendered layouts/_header.html.erb (Duration: 0.8ms | Allocations: 318)
Rendered layouts/_footer.html.erb (Duration: 0.8ms | Allocations: 258)
Rendered layout layouts/application.html.erb (Duration: 18.8ms | Allocations: 11238)
Completed 200 OK in 35ms (Views: 23.0ms | ActiveRecord: 0.8ms | Allocations: 16412)
寶石檔案:
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby "3.0.3"
gem "rails", "~> 7.0.1"
gem "sprockets-rails"
gem "puma", "~> 5.0"
gem "importmap-rails"
gem "turbo-rails" # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "stimulus-rails" # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "jbuilder" # Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "bootsnap", require: false
gem "sassc-rails" # Use Sass to process CSS
gem 'image_processing'#, '1.9.3'
gem 'mini_magick'#, '4.9.5'
gem 'active_storage_validations'#, '0.8.9'
gem 'bcrypt'#, '3.1.13'
gem 'faker'#, '2.11.0'
gem 'will_paginate'#, '3.3.0'
gem 'bootstrap-will_paginate'#, '1.0.0'
gem 'bootstrap-sass'#, '3.4.1'
group :development, :test do
gem "sqlite3", "~> 1.4"
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end
group :development do
gem "web-console"
gem "rack-mini-profiler"
gem "spring"
end
group :test do
# Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
gem "capybara"
gem "selenium-webdriver"
gem "webdrivers"
gem 'rails-controller-testing'#, '1.0.5'
gem 'minitest'#, '5.11.3'
gem 'minitest-reporters'#, '1.3.8'
gem 'guard'#, '2.16.2'
gem 'guard-minitest'#, '2.4.6'
end
group :production do
gem "pg"
gem 'aws-sdk-s3', require: false
end
應用程式/資產/樣式表/custom.scss:
@import "bootstrap-sprockets";
@import "bootstrap";
/* mixins, variables, etc. */
$gray-medium-light: #eaeaea;
/* universal */
body {
padding-top: 60px;
}
section {
overflow: auto;
}
textarea {
resize: vertical;
}
.center {
text-align: center;
h1 {
margin-bottom: 10px;
}
}
@mixin box_sizing {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
/* typography */
h1, h2, h3, h4, h5, h6 {
line-height: 1;
}
h1 {
font-size: 3em;
letter-spacing: -2px;
margin-bottom: 30px;
text-align: center;
}
h2 {
font-size: 1.2em;
letter-spacing: -1px;
margin-bottom: 30px;
text-align: center;
font-weight: normal;
color: $gray-light;
}
p {
font-size: 1.1em;
line-height: 1.7em;
}
/* header */
#logo {
float: left;
margin-right: 10px;
font-size: 1.7em;
color: white;
/* text-transform: uppercase; */
letter-spacing: -1px;
padding-top: 9px;
font-weight: bold;
&:hover {
color: white;
text-decoration: none;
}
}
/* footer */
footer {
margin-top: 45px;
padding-top: 5px;
border-top: 1px solid #eaeaea;
color: $gray-light;
a {
color: $gray;
&:hover {
color: $gray-darker;
}
}
small {
float: left;
}
}
footer ul {
float: right;
list-style: none;
}
footer ul li {
float: left;
margin-left: 15px;
}
/* Forms */
input, textarea, select, .uneditable-input {
border: 1px solid #bbb;
width: 100%;
margin-bottom: 15px;
@include box_sizing
}
input {
height: auto !important;
}
#error_explanation {
color: red;
ul {
color: red;
margin: 0 0 30px 0;
}
}
/*
.field_with_errors {
@extend .has-error; /*this is breaking
/*potential solution? https://jasoncharnes.com/bootstrap-4-rails-fields-with-errors/
.form_control {
color: $state-danger-text;
}
}
*/
/* Miscellaneous */
.debug_dump {
clear: both;
float: left;
width: 100%;
margin-top: 45px;
@include box_sizing;
}
應用程式/控制器/users_controller.rb:
class UsersController < ApplicationController
def new
@user = User.new
end
def show
@user = User.find(params[:id])
end
def create
@user = User.new(user_params) #strong params required by Rails
#debugger
if @user.save
#handle succesful save
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:email, :first_name, :last_name, :phone_number, :admin)
end
end
Edit Ok, I have confirmed by inserting test pieces into the code that this is something to do with HTML rendering. It is definitely not an issue with the instance variable passing into the partial (although I've now learned why that's poor practice!). Example below outputs to the command line exactly as expected, however the plaintext "False" doesn't change to "True" when erroneous data is submitted in the form. It almost seems like this is something with Ajax or similar where the form is submitted and the ruby/rails runs, but the html isn't refreshed? Furthermore - I've now written tests for the errors to appear and the tests pass! This is messing with my head.
app/views/shared/_error_messages.html.erb:
<% puts @user.errors.any? %>
<% if @user.errors.any? %>
True
<% puts @user.errors.count %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(@user.errors.count, "error") %>
</div>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% else %>
<% puts @user.email %>
False
<% end %>
uj5u.com熱心網友回復:
試試這個app/views/users/new.html.erb
<%= render 'shared/error_messages', user: @user %>
如果它是共享部分,則可能使實體變數通用而不是通用 @user。這樣它就可以被重復使用,并且在以后減少混亂。
uj5u.com熱心網友回復:
解決了!這是 Rails 7(而不是 Turbolinks)中 Turbo / Hotwire 的問題。在用戶控制器中,我必須更改渲染呼叫以包含狀態::unprocessable_entity。這種行為現在完美無缺。
def create
@user = User.new(user_params) #strong params required by Rails
#debugger
if @user.save
#handle succesful save
else
render 'new', status: :unprocessable_entity
end
end
感謝所有評論的人。即使在部分中使用實體變數不是問題,我確實閱讀并了解了為什么這是不受歡迎的做法,非常值得。
我從這個stackoverflow評論中找到了答案: 在Rails 7中提交表單后渲染視圖無法正常作業
uj5u.com熱心網友回復:
locals在您的渲染中使用:
render partial: 'shared/error_messages', locals: { user: @user }
并通過重shared/error_messages命名。@useruser
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424097.html
標籤:ruby-on-rails railstutorial.org ruby-on-rails-7
