[英]Devise gem admin can add user into user model
我正在使用devise
gem 在 Rails 中進行身份驗證。 我想創建一個可以將用戶添加到User
模型的管理儀表板。 我能夠將表單呈現到admin#index
視圖中,但我無法在用戶模型中插入數據。
路由文件
# when i use post method in this route i get routing error
get '/admin' => "admin#index", as: :create_user
管理 index.html.erb
<%= form_for User.new, url: create_user_path do |f| %>
<div class="log-in-form">
<h2 class="login-header text-center">Sign up</h2>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :password %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "new-password" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
admin_controller.rb
def index
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if User.save
redirect_to root_path
else
render :new
end
end
private
def user_params
params.require(:user).permit(:name,:password)
end
先生,您非常需要閱讀並理解這一點: https : //guides.rubyonrails.org/routing.html
回答:
您已自己將路由定義為get
方法,並且希望post
到它。 你在這里看到一些很奇怪的東西嗎? 作為初學者,盡量不要偏離 rails 為您提供的基本 CRUD 路線。 在您的情況下,請在routes.rb
執行此routes.rb
:
resources :users
# OR:
# resources :users, only: %i[index show create update destroy]
# any names of CRUD functions that you probably will use (to avoid extra routes)
現在,在您的 html 文件url: users_path
url: create_user_path
更改為url: users_path
。 順便說一句,至少要養成在終端中檢查路線的習慣,例如: rails routes | grep user
rails routes | grep user
會給你包含單詞 user 的 rails 路線。
它現在應該可以工作了。
在您的 config/routes.rb 中添加以下行
post '/admin' => 'admin#index'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.