0

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

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

顺便说一下,txt 是 UTF8 编码的。

可能是配方关联的 counter_cache 吗?

导轨 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

耙文件:

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
4

0 回答 0