我对rails和编程很新,并且在rails控制台配置中有一点麻烦,以便将自己标识为管理员。执行user.save命令后,我的管理员值仍然是假的,我得到一个控制台注释,上面写着。
控制台
void myMethod(Object... params){
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("myMethod() - [");
for (int i=0; i<params.length; i++) {
strBuilder.append("param"+(i+1)+": "+params[i]+",");
}
strBuilder.deleteCharAt(strBuilder.length()-1); //last comma deleted
strBuilder.append("]");
logger.info(strBuilder.toString());
}
这是我到目前为止所做的。
_add_admin_to_users.rb
0.2ms) begin transaction
(0.1ms) rollback transaction
=> false
Rails控制台管理员保存过程
class AddAdminToUsers < ActiveRecord::Migration
def change
add_column :users, :admin, :boolean, default: false
end
end
user.rb
user = User.find_by(email: 'your-eamiladdress@example.tld')
user.admin = true
user.save
user.admin?
答案 0 :(得分:1)
有一些验证或保存失败所以所有进程都取消了,你可以看到有这样的文字:
(0.1ms) rollback transaction
=> false
It means save process rollback
Use user.save! to see error and it seems to me error due to validation on name field of user
试试这个:
user = User.find_by(email: 'your-eamiladdress@example.tld')
user.name = "Admin"
user.admin = true
user.save
user.admin?
答案 1 :(得分:0)
您可以通过转发验证来尝试此操作
user = User.find_by(email: 'your-eamiladdress@example.tld')
user.admin = true
现在在rails&lt; 3
user.save(false)
user.admin?
或者在rails 3之后
user.save(:validate => false)
user.admin?
或者如果您不想逃避验证
user = User.find_by(email: 'your-eamiladdress@example.tld')
user.name = "Admin"
user.admin = true
user.save
user.admin?