我正在用Rails做一個待辦事項列表。因此我製作了一個用戶模型(電子郵件和密碼)。我希望用戶能夠編輯帳戶,所以我在用戶控制器上進行了編輯和更新操作,我也有一個用戶模型。一切都很好,但我的問題是,在設置視圖中,用於更新電子郵件的text_field已經預先填好了模型中的當前電子郵件地址。由於設計方面的原因,我想禁用預填充(佔位符的內容應該立即可讀)。我知道當我解決這個問題時,用戶模型會出現另一個問題。例如,如果用戶只想更改密碼,用戶將收到一條錯誤消息,如:「電子郵件不能爲空」和「電子郵件無效」...我可以修改密碼的最小長度驗證如果密碼爲空,因爲我知道「has_secure_password」在創建對象時強制執行存在驗證。所以我知道新用戶將無法使用空白密碼進行註冊。但是,我怎樣才能爲電子郵件驗證創建相同的效果?我還沒有找到解決方案,如果有人能幫助我,我將不勝感激。提前致謝!如何禁用Rails中的預填表單字段?
問題:
- 如何禁用Rails的預充的形式?
- 應該修改什麼來接受設置表格 中的空白電子郵件,而不將電子郵件更新爲數據庫中的空白?
users_controller.rb(控制器)
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated!"
redirect_to @user
else
render 'edit'
end
end
edit.html.erb(視圖)
<% provide(:title, "Settings") %>
<h4>SETTINGS</h4>
<h5>User Edit</h5>
<%= @user.email %>
<div class="settings">
<%= form_for(@user) do |f| %>
<%= render 'layouts/error_messages' %>
<p>Change Email:</p>
<%= f.text_field :email, placeholder: "New Email", class: "formfield" %>
<p>Change Password:</p>
<%= f.password_field :password, placeholder: "New Password", class: "formfield" %>
<%= f.password_field :password_confirmation, placeholder: "New Password Confirmation", class: "formfield" %>
<%= f.submit "Save Changes", class: "form_button" %>
<% end %>
<%= link_to "Delete my Account", '#' %>
</div>
user.rb(模型)
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }, allow_blank: true
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end
當你使用form_for的時候,它會綁定並在視圖中顯示模型值.. – Milind