Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

Rails form doesn't display in the view

Similar to Rails: form doesn't show up post, I've run into a similar issue but can't figure out what I'm doing wrong. the only thing in the view that shows up is the h1 "New User".

.container.mt-4
  %h1 New User

  = form_for([:admin, @user]) do |f|
    - if @user.errors.any? 
      #error_explanation
        %h2 #{pluralize(@user.errors.count, "error")} prohibited this user from being saved:
        %ul
          - @user.errors.full_messages.each do |msg|
            %li %{msg
          .field
            = f.label :email 
            = f.text_field :email
          .field
            = f.label :password 
            = f.password_field :password 
          .field
            = f.label :password_confirmation 
            = f.password_field :password_confirmation 
          .action
            = f.submit 
    

here's my users controller in admin

class Admin::UsersController < ApplicationController
  def index
    @users = User.all
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        format.html { redirect_to admin_users_url, notice: 'User was successfully created.' }
        format.json { render json: @user, status: :created, location: [:admin,@user] }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

Like in the other post, Rails no longer raises errors after I fixed the syntax errors it complained about.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because if your nesting, your form will only show up if user has errors.

I imagine you actually want something like this:

.container.mt-4
  %h1 New User

  = form_for([:admin, @user]) do |f|
    - if @user.errors.any? 
      #error_explanation
        %h2 #{pluralize(@user.errors.count, "error")} prohibited this user from being saved:
        %ul
          - @user.errors.full_messages.each do |msg|
            %li %{msg}
    .field
      = f.label :email 
      = f.text_field :email
    .field
      = f.label :password 
      = f.password_field :password 
    .field
      = f.label :password_confirmation 
      = f.password_field :password_confirmation 
    .action
      = f.submit 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...