在开始之前:是的,我知道这不是存储用户名和密码的安全方法。
继续,我正在尝试建立一个系统,该系统将允许我使用用户名,密码和值创建帐户,然后显示每个帐户的用户名和值。我已经到了要创建一个新模板的地步,因为缺少一个更好的词来显示用户名和值,但是实际上什么也没有显示。我的控制器:
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
中的数据确实可以正确显示,只是创建的帐户无法正常工作。
答案 0 :(得分:1)
我认为这里的问题之一是account_parameters
白名单。
permit(*filters)
接受代表允许参数的符号集合。它看起来应该像permit(:username, :password)
。通过对permit
的结果调用permit
,我相信这段代码将过滤到:username
,然后从该列表中尝试提取:password
,同时丢失两个值过程。
尝试将该功能更改为:
private def account_params
params.require(:account).permit(:username, :password)
end