在我开始讨论之前:是的,我知道这不是存储用户名和密码的安全方法。
继续,我正在尝试设置一个允许我使用用户名,密码和值创建帐户的系统,然后显示每个帐户的用户名和值。我已经到了创建新模板的地步,因为缺少更好的单词,显示用户名和值,但实际上没有显示任何内容。我的控制器:
class TestController < ApplicationController
def index
@accounts = Account.all
end
def new
@account = Account.new
end
private def account_params
params.require(:account).permit(:username).permit(:password)
end
def create
@account = Account.new(account_params)
if @account.save
redirect_to '/index'
else
render 'new'
end
end
end
我的形式:
<%= form_for(@account) do |f| %>
<div class="field">
<h3>Username:</h3>
<%= f.text_area :username %><br>
<h3>Password:</h3>
<%= f.text_area :password %>
</div>
<div class="action">
<%= f.submit "Create" %>
</div>
<% end %>
最后,我的迁移文件:
class CreateAccounts < ActiveRecord::Migration[5.2]
def change
create_table :accounts do |t|
t.string :username
t.string :password
t.integer :value
end
end
end
显示每个帐户的实际代码:
<% @accounts.each do |t| %>
<div class="accountbox">
<strong>Username:</strong><%= t.username %><br>
<br>
<strong>Value:</strong> <%= t.value %><br>
</div>
<% end %>
路线:
Rails.application.routes.draw do
get 'index' => 'test#index'
get 'new' => 'test#new'
post 'accounts' => 'test#create'
end
哦,我应该注意db/seed.rb
中的数据确实正确显示,它只是创建的不起作用的帐户。
我认为这里的部分问题是account_parameters
白名单。
permit(*filters)
采用代表允许参数的符号集合。它看起来应该像permit(:username, :password)
。通过在permit
的结果上调用permit
,我相信这个代码正在过滤到:username
,然后从该列表中试图拉出:password
,在此过程中丢失两个值。
尝试将该功能更改为:
private def account_params
params.require(:account).permit(:username, :password)
end