我有一个标准的Rails3环境,RVM 1.2.9,Rails 3.0.5,Ruby 1.9.2p180,MySQL2 Gem 0.2.7,mysql-5.5.10-osx10.6-x86_64
运行rake db:migrate创建数据库时出现的错误是:
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) config / database.yml有
development: adapter: mysql2 host: localhost username: root password: xxxx database: xxxx 确保这是我想念的简单事情。
该where子句永远不会返回nil,它返回一个ActiveRecord :: Relation对象,该对象可以为空!
尝试以下方法:
def create if @trained = Certificate.where(user_id: params[:certificate][:user_id]).first @trained.update_attributes(attend: "No") else @trained = Certificate.new(params[:certificate]) if @trained.save @trained.update_attributes(attend: "Yes") end end
redirect_to grandstreamers_resellers_path end 但我会将代码重构为如下形式:
def create @trained = Certificate.where(user_id: params[:certificate][:user_id]).first @trained ||= Certificate.new(params[:certificate]) if @trained.persisted? # tests if the records is persisted in the DB (has an ID) @trained.attend = "No" else @trained.attend = "Yes" end
@trained.save redirect_to grandstreamers_resellers_path end 非常简短的版本:
def create @trained = Certificate.where(user_id: params[:certificate][:user_id]).first || Certificate.new(params[:certificate]) @trained.attend = @trained.persisted? ? "No" : "Yes" @trained.save
redirect_to grandstreamers_resellers_path end 为了记录(@NitinJ,请看一下),您可以在if条件中分配变量:
if first_user = User.first
first_user.id else # User.first returned nil end来源:stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。