ERB 不显示实例变量值

ERB not showing instance variable values

@user 当我显示为 HTML 时显示为 nil。但是,当我将它输出到 rails 服务器时,它拥有正确的值。

new.html.erb

<% u = @user.username %>
<% puts u %>
<p> <%= u %> </p>

<%= form_with model: @user do |f| %>
  <%= f.label 'username', 'Username:' %>
  <%= f.text_field :username, :value => 'Enter Your Username' %>
  <%= f.label 'email', 'Email:' %>
  <%= f.email_field :email, :value => 'example@example.com' %>

  <%= f.label 'password', 'Password:' %>
  <%= f.password_field :password %>
  <%= f.submit 'Submit' %>
<% end %>

schema.rb

 create_table "users", force: :cascade do |t|
    t.string "username"
    t.string "email"
    t.string "password_digest"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["username"], name: "index_users_on_username", unique: true
  end

users_controller.rb

  def new
    @user = User.new
  end

  def create
    @user = User.new(whitlisted_user_params)
    if @user.save
      redirect_to new_user_path
    else
      render :new
    end


private 

  def whitlisted_user_params
    params.require(:user).permit(:username, :email, :password)
  end

rails 服务器上的输出

Vedant

在网页上输出

<p> </p>

找出问题所在并将其张贴在这里供其他人使用。

如果你查看服务器日志,它会有一行

Processing by UserController#create as JS.

发生这种情况是因为 form_with(不同于 form_for & form_tag)默认使用 XHR(Ajax) 提交数据。实际发生的是渲染没有执行整页刷新

这是使用 form_with 的附加优势之一。

Rails Issue #25197

Full-page changes after submissions are rough. When using Turbolinks, a normal redirect will generate a Turbolinks.visit() call, and otherwise there's SJR. (We could consider having config.action_view.forms_remote_by_default that you could set to false, for people going old school).

现在有两种显示错误的方式

(快速修复)本地:true

local: true 添加到禁用遥控器的 form_with 代码:默认为 true 功能

改变

<%=form_with model: @user do |f| %>

<%=form_with model: @user, local:true do |f| %>

更好的拥抱方式AJAX

https://m.patrikonrails.com/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38