Pergunta

Hi I have a rails app which contains a Channel model. Its attributes are as 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 my app has read a csv file and populated information in the database. This is a snapshot of the code that creates the 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 for row #{i} was nil"
       next 
    else                                    
       puts "Creating channel hash with information:"
   puts "channel_name= #{channelName}"
   puts "classification=#{classif}"
   puts "ownership= #{owner}"

   ch = Channel.where(:channel_name =>"#{channelName}").first_or_create do |c|
   c.ownership = "#{owner}"
   c.classification = "#{classif}"

Since the task was able to read the csv file and populate the database, the "create" part of the "first_or_create" method works. However, when I change some things in the csv file and redo the rake task, it should update the database with the changed contents. Its not doing this. Im wondering is it something to do with the syntax of my method? is the block part wrong?

Foi útil?

Solução

The documentation for first_or_create doesn't say that it updates the record if it already exists. It

  1. creates the record if it doesn't exist.
  2. Returns the record if it exists already

You would have to update it after you get the record.

ch = Channel.where(:channel_name =>"#{channelName}").first_or_create do |c|
   c.ownership = "#{owner}"
   c.classification = "#{classif}"
end

ch.update_attribute(:attr, value)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top