lll*_*lll 2 ruby-on-rails update-attributes
我正在一个用户可以拥有的项目中工作admin: true / false.该应用程序只允许管理员用户登录系统,其他用户只是其设置只有管理员可以编辑的客户端.这是某种商业应用程序.(Rails 3.2.13)
我想将这两个概念保存在同一个表中,因为将来可能会选择登录非管理员用户并与他们的配置文件进行交互,因此所有逻辑都已经实现.
我有这个User资源:
ActiveRecord::Schema.define(:version => 20131204200554) do
create_table "users", :force => true do |t|
t.string "name"
t.string "surname"
t.boolean "admin"
t.string "password_digest"
t.string "email"
t.string "auth_token"
end
end
Run Code Online (Sandbox Code Playgroud)
这是用户模型:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :name, :surname,:email, :password, :password_confirmation
validates :name, presence:true, length: { maximum:50}
validates :first_surname, presence:true, length: { maximum:50}
VALID_EMAIL_REGEX= /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive:false}
validates :password, length:{minimum:6}
validates :password_confirmation, presence:true
before_save{ self.email.downcase! }
before_save :generate_auth_token
private
def generate_auth_token
self.auth_token=SecureRandom.urlsafe_base64
end
end
Run Code Online (Sandbox Code Playgroud)
我正在尝试实现User编辑功能,但我只想允许编辑name,surname和email.因此,我只提供以下形式的字段:
<%= form_for(@user) do |f| %>
<%= f.label :name,"Name" %>
<%= f.text_field :name %>
<%= f.label :surname,"Surname" %>
<%= f.text_field :surname %>
<%= f.label :email,"Email" %>
<%= f.text_field :email %>
<%= f.submit "Save" %>
Run Code Online (Sandbox Code Playgroud)
我试图用这段代码完成目标:
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
# Handle a successful update.
flash[:success]="User updated successfully"
redirect_to @user
else
flash[:danger]="Error updating user"
render 'edit'
end
end
Run Code Online (Sandbox Code Playgroud)
我的问题是,当尝试update_attributes,我得到不意外的错误验证password/password_confirmation,但因为我使用has_secure_password,这些字段不会在数据库中只存在,password_digest.我正在考虑完成所有这些的最佳选择:
@user使用新字段值更新对象.User表格中反映这一变化.使用时has_secure_password.到目前为止这些是选项:
update_attribute(最好到目前为止).User表update_attribute(field1)为每个字段,所以更多的代码行@user.attributes=params[:user]控制器方法User表格.update_attributes建议?
看起来您只想在创建时验证密码的存在(还要注意更简洁的方式来验证密码确认):
validates :password, length:{minimum:6}, confirmation: true, on: :create
Run Code Online (Sandbox Code Playgroud)
然后你可以使用 update_attributes
您可能希望使用强参数来限制可以提交的参数:
| 归档时间: |
|
| 查看次数: |
2868 次 |
| 最近记录: |