保存记录..但不保存...... :(

时间:2013-01-06 20:32:58

标签: mysql ruby-on-rails ruby

我有一个模型的静态方法,它创建了多个记录。保存父节点时调用此方法,将用于创建适当n个子记录的数据传递给此方法(new_record),然后迭代传递给它的数组,并创建子记录。

Job有很多工作活动。此方法new_record属于job_activities模型,并在保存作业记录时在job_controller中调用。基本上尝试以单一形式实现两个模型。作业“has_many”job_activities,Job_activites“belongs_to”作业。

这是我到目前为止所放在一起的内容 -

       def self.new_record(sk_job_id, activities_list)
        activities_list.each do | act |
          puts "AAAAAAAAAAAAAAAAAAAAAAA creating a new record for "+act.inspect+" and " + sk_job_id.to_s
            ja = JobActivity.new
            puts "Job ID SK = "+sk_job_id.to_s
            puts "act = "+act
            puts "Record before assignment "+ ja.inspect
            ja.job_id_sk = sk_job_id
            ja.job_activity = act
            ja.created_by  = "raghav"
            ja.updated_by  = "raghav"
            puts "Record after assignment "+ ja.inspect            
            ja.save!
            puts "record after saving "+ ja.inspect
        end
      end

奇怪的是,对象ja的前后分配状态反映了“created_by”的赋值,但没有反映job_id_sk和job_activity的赋值......

而且,正如所建议的那样,我实施了保存!但这没有引起任何例外..它仍然非常默默地表现它做的...... :(

AAAAAAAAAAAAAAAAAAAAAAA creating a new record for "ACT1" and 40
Job ID SK = 40
act = ACT1
Record before assignment #<JobActivity id: nil, job_id_sk: nil, job_activity: nil, created_by: nil, updated_by: nil, created_at: nil, updated_at: nil>

Record after assignment #<JobActivity id: nil, job_id_sk: nil, job_activity: nil, created_by: "raghav", updated_by: "raghav", created_at: nil, updated_at: nil>

record after saving #<JobActivity id: 13, job_id_sk: nil, job_activity: nil, created_by: "raghav", updated_by: "raghav", created_at: "2013-01-08 02:22:30", updated_at: "2013-01-08 02:22:30">

但是,当我去检查应该保存数据的mysql表时,我发现只传递了NULL值......

mysql> select job_id_sk, job_activity from job_activities;
+-----------+--------------+
| job_id_sk | job_activity |
+-----------+--------------+
|      NULL | NULL         |
|      NULL | NULL         |
|      NULL | NULL         |
|      NULL | NULL         |
|      NULL | NULL         |
+-----------+--------------+
5 rows in set (0.00 sec)

我错过了什么地方吗?

2 个答案:

答案 0 :(得分:0)

model#save返回true或false,但model#save!(请注意方法名称末尾的!)将引发异常,而不是返回false。

可能是模型未通过验证或设置不正确。使用save!将立即显然失败,告诉你实际上有什么错误。

答案 1 :(得分:0)

发现问题,解决方案......

我正在使用attr_accessor作为模型,而我本应该使用attr_accessible ......

詹姆斯对这个问题的回应帮助了我..

Called .save on a ruby object is only passing nil for all strings