csv - ruby first_or_create method not updating the model & database -


hi have rails app contains channel model. attributes follows:

   # table name: channels    #    #  id             :integer          not null, primary key    #  created_at     :datetime    #  updated_at     :datetime    #  channel_name   :string(255)    #  classification :string(255)      default("0")    #  ownership      :string(255)      default("0") 

a rake task in app has read csv file , populated information in database. snapshot of code creates model

    ...previous code........      channelname = nil     classif = nil     owner = nil     channelname = row[0].force_encoding('utf-8')     classif = row[1].force_encoding('utf-8')     owner = row[2].force_encoding('utf-8')   if (channelname.nil?)        puts "channel name row #{i} nil"        next      else                                            puts "creating channel hash information:"    puts "channel_name= #{channelname}"    puts "classification=#{classif}"    puts "ownership= #{owner}"     ch = channel.where(:channel_name =>"#{channelname}").first_or_create |c|    c.ownership = "#{owner}"    c.classification = "#{classif}" 

since task able read csv file , populate database, "create" part of "first_or_create" method works. however, when change things in csv file , redo rake task, should update database changed contents. not doing this. im wondering syntax of method? block part wrong?

the documentation first_or_create doesn't updates record if exists. it

  1. creates record if doesn't exist.
  2. returns record if exists already

you have update after record.

ch = channel.where(:channel_name =>"#{channelname}").first_or_create |c|    c.ownership = "#{owner}"    c.classification = "#{classif}" end  ch.update_attribute(:attr, value) 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -