Rake任务只导入一行txt文件

时间:2013-03-05 22:21:03

标签: ruby-on-rails ruby-on-rails-3 import rake rake-task

我写了很多简单的rake文件来将txt文件导入我的mysql。 除了一个型号外,一切都很完美。 我没有错误所以我不知道发生了什么。

rake只导入第一行。其他一切都没有!

顺便说一句,txt采用UTF8编码。

可能是食谱关联的counter_cache吗?

RAILS 3.1

型号:

class Recipe < ActiveRecord::Base
    belongs_to :chef, :counter_cache => true
    belongs_to :category, :counter_cache => true
    belongs_to :cuisine, :counter_cache => true
    belongs_to :festivity, :counter_cache => true
    belongs_to :daily, :counter_cache => true

    after_update :update_counter

    # Setup accessible (or protected) attributes for your model
    attr_accessible :name,
                    :slug,
                    :description,
                    :ingredients,
                    :steps,
                    :...
                    :status_id,
                    :created_at,
                    :updated_at

    STATUS = { 'Não publicada' => 0, 'Publicada' => 1, 'Invisível' => 4 }
    def status
        STATUS.invert[status_id]
    end

    private

    def update_counter
        if category_id_changed?
            Category.increment_counter(:recipes_count, category_id)
            Category.decrement_counter(:recipes_count, category_id_was)
        end
        if cuisine_id_changed?
            Cuisine.increment_counter(:recipes_count, cuisine_id)
            Cuisine.decrement_counter(:recipes_count, cuisine_id_was)
        end
        if festivity_id_changed?
            Festivity.increment_counter(:recipes_count, festivity_id)
            Festivity.decrement_counter(:recipes_count, festivity_id_was)
        end
        if daily_id_changed?
            Daily.increment_counter(:recipes_count, daily_id)
            Daily.decrement_counter(:recipes_count, daily_id_was)
        end
    end
end

RAKE文件:

namespace :db do
    desc "import data from files to database"
    task :import_recipe => :environment do
        puts "Importing Recipe..."
        # recipe.txt
        File.open("lib/tasks/data/recipe.txt", "r").each do |line|
            id, name, slug, description, ingredients, steps, other_tips, cook_time, recipe_yield, diet, light, lactose_intolerance, vegetarian, microwave, video_url, chef_id, category_id, cuisine_id, festivity_id, daily_id, likes_count, rating, ratings_count, views_count, comments_count, status_id, created_at, updated_at = line.strip.split("\t")
            d = Recipe.new(
                :id => id,
                :name => name,
                :slug => slug,
                :description => description,
                :ingredients => ingredients,
                :steps => steps,
                :...
                :status_id => status_id,
                :created_at => created_at,
                :updated_at => updated_at
                )
                d.save!
            end
        puts "=========== > FINISHED!"
    end
end

0 个答案:

没有答案