Ruby-on-rails Rails 控制台中手动更新属性值的验证问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15110858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation problems on manual update of attribute value in Rails console
提问by Marcin Doliwa
I have a simple problem. I want to change some field value for my User.find(1)in rails console.
我有一个简单的问题。我想为我的User.find(1)in rails 控制台更改一些字段值。
I tried:
我试过:
u = User.find(1)
u.update_attributes(roles_mask: 3)
And got falsereturned. When I check u.errors.full_messages, I see that it's because there is a problem with password validation from has_secure_password. How can I update it manually in the console?
并被false退回。当我检查 时u.errors.full_messages,我看到这是因为has_secure_password. 如何在控制台中手动更新它?
回答by jvnill
if you want to bypass validation, use
如果要绕过验证,请使用
# skip validations but run callbacks
u.update_attribute :roles_mask, 3
or
或者
# do the update on the sql so no validation and callback is executed
u.update_column :roles_mask, 3
回答by Muhamamd Awais
You have to authenticate the user first then you can update the user have a look here
您必须先对用户进行身份验证,然后才能更新用户,请查看此处
u = User.find(1)
u.authenticate("password")
u.update_attributes(roles_mask: 3)
Or if you want to skip the validations you can do as follow;
或者,如果您想跳过验证,您可以执行以下操作;
u = User.find(1)
u.update_attribute :roles_mask, 3
回答by alestanis
You can try update_attribute(:roles_mask, 3)or update_column(:roles_mask, 3).
你可以试试update_attribute(:roles_mask, 3)或update_column(:roles_mask, 3)。
回答by Tarun Rathi
You can have something like this
你可以有这样的东西
Post.find(1).comments.first.update(body: "hello")
or
或者
@u = Post.find(1)
@u.comments.first.update(body: "hello")
where comments is the name of the comment table, body is the name of column in the comment table.
其中comments 是评论表的名称,body 是评论表中的列名。
This applies when you have nested attribute
当您有嵌套属性时,这适用
post.rb
后.rb
has_many: comments
accept_nested_attributes_for: comment
comment.rb
评论.rb
belongs_to: post

