I have this static method for a model, which is creating multiple records. This method is called when saving the parent, the data for creating appropriate n child records is passed to this method (new_record) which then iterates through the array passed to it, and creates the child records.
Job has many Job Activities. This method new_record belongs to job_activities model and is invoked in job_controller, when saving job record. Basically trying to implement two models in a single form. Job “has_many” job_activities, and Job_activites “belongs_to” a job.
Here’s what I have put together so far –
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
Weird thing happening is, that the before and after assignment state of the object ja, reflects the assignment of “created_by” but not of job_id_sk and job_activity…
And, as suggested, I implemented the save! but that didnt raise any exceptions.. its still quite silently behaving what its doing… 🙁
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">
However, when I go and check the mysql table where the data should have been saved, I see that only NULL values have been passed in…
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)
Am I missing something somewhere ?
Found the problem, and the solution…
I was using attr_accessor for the model, whereas I should have been using attr_accessible…
Response from James on this question helped me..
Called .save on a ruby object is only passing nil for all strings