我遇到了rails的問題:我試圖爲個人使用和學習rails的密碼管理做一個應用程序,我希望密碼被加密(用於現在我正在使用河豚算法)。我已經安裝了crypt gem並編寫了一些代碼,但是我收到了一個奇怪的錯誤。Rails:未定義的方法`%'爲true:TrueClass
這裏是我的代碼:
應用程序/控制器/ credentials_controller.rb(腳手架生成)
def create
@credential = current_user.credentials.build(params[:credential])
respond_to do |format|
if @credential.save
format.html { redirect_to(@credential, :notice => 'Credential was successfully created.') }
format.xml { render :xml => @credential, :status => :created, :location => @credential }
else
format.html { render :action => "new" }
format.xml { render :xml => @credential.errors, :status => :unprocessable_entity }
end
end
end
應用程序/模型/ credential.rb(在DB我創建了一個鹽:字符串列)
require 'crypt/blowfish'
class Credential < ActiveRecord::Base
before_save :hash_password
before_update :hash_password
after_find :unhash_password
private
def hash_password
self.salt = ActiveSupport::SecureRandom.base64(8)
blowfish = Crypt::Blowfish.new(self.salt)
self.pass = blowfish.encrypt_block(self.pass)
end
def unhash_password
end
end
應用/視圖/憑證/ _form.html.erb
<%= form_for(@credential) do |f| %>
<% if @credential.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@credential.errors.count, "error") %> prohibited this credential from being saved:</h2>
<ul>
<% @credential.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul >
</div>
<% end %>
<div class="field">
<%= f.label :servizio %><br />
<%= f.text_field :servizio %>
</div>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :utente %><br />
<%= f.text_field :utente %>
</div>
<div class="field">
<%= f.label :pass %><br />
<%= f.text_field :pass %>
</div>
<div class="field">
<%= f.label :note %><br />
<%= f.text_area :note %>
</div>
<div class="field">
<%= collection_select(:credential, :group_id, current_user.groups, :id, :nome, prompt => 'Seleziona Gruppo') %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
的錯誤是:
`Action Controller: Exception caught
NoMethodError in CredentialsController#create
undefined method '%' for true:TrueClass
app/models/credential.rb:17:in 'hash_password'
app/controllers/credentials_controller.rb:47
app/controllers/credentials_controller.rb:46:in 'create'
注意:如果在證書模型
def hash_password
self.salt = ActiveSupport::SecureRandom.base64(8)
plainBlock = "ABCD1234"
blowfish = Crypt::Blowfish.new(self.salt)
self.pass = blowfish.encrypt_block(plainBlock)
end
它的工作原理,但密碼(顯然)總是ABCD1234。上面的代碼意味着問題是blowfish.encrypt_block函數中的self.pass。
我在做什麼錯?
如果我跳過before_save函數,它將作爲非加密密碼工作,所以我排除了與路由相關的問題。
非常感謝你!
最好的問候!
PS:我使用Rails 3.0.8 PS:我下面這個頁面http://crypt.rubyforge.org/blowfish.html
貌似這個問題實際上是在你上面沒有包括代碼發生。 Credential模型中的'hash_password'函數是什麼?你應該編輯你的文章以包含它。 – ipd
非常感謝你的ipd。現在代碼是正確的。 – franc
恩,當然,問題是什麼? – ipd