开发者

Ruby on rails save data inside loop

   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

here is the code but inside loop data is not saving only one record is saved.


I believe you have to add

@user_work_history = UserWorkHistory.new

to the first line inside the loop. (or whatever the model is)


When you do that kind of loop you need to change the reference to the instance variable @user_work_history. What your loop does is that for each iteration it updates the state of the same object!

What you should do, is to set the @user_work_history before each iteration, like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜