Ruby on rails在循环中保存数据

时间:2010-11-29 10:43:42

标签: ruby-on-rails

   object.each do |info|
     @user_work_history.fb_user_id = facebook_session.user.id
     @user_work_history.city = info.location.city
     @user_work_history.country = info.location.state
     @user_work_history.company_name = info.company_name
     @user_work_history.description = info.description
     @user_work_history.start_date = info.start_date
     @user_work_history.end_date = info.end_date
     @user_work_history.position = info.position
     @user_work_history.updated_at = Time.now
     @user_work_history.save
   end

这里是代码,但内部循环数据不保存只保存一条记录。

2 个答案:

答案 0 :(得分:2)

我相信你必须添加

@user_work_history = UserWorkHistory.new

到循环内的第一行。 (或任何模型)

答案 1 :(得分:2)

当你进行这种循环时,你需要改变对实例变量 @user_work_history 的引用。你的循环所做的是每次迭代都会更新同一个对象的状态!

你应该做的是在每次迭代之前设置 @user_work_history ,如下所示:

object.each do |info|
     @user_work_history = UserWorkHistory.new(:fb_user_id => facebook_session.user.id) # for example
     @user_work_history.city = info.location.city
     @user_work_history.country = info.location.state
     (...)
     @user_work_history.save # here it saves new tuple
end