如何在rake任务中使用ActiveStorage将图像附加到对象?

时间:2018-09-28 16:44:14

标签: ruby-on-rails ruby activeadmin rails-activestorage

我正在使用ActiveAdmin和ActiveStorage管理应用程序中的Card对象。通过ActiveAdmin界面创建具有其所有属性(包括图像)的新卡时,它可以正常工作。但是,当我尝试使用rake任务为数百张卡片播种数据库时,它失败了,我得到ActiveSupport::MessageVerifier::InvalidSignature: ActiveSupport::MessageVerifier::InvalidSignature

popdb.rake:

desc 'Populate db'
task :popdb => [:environment] do 
    puts 'Generating categories...'

    5.times do
        category = Category.create(title: Faker::Color.color_name)
        puts "Created category \"" + category.title + "\""
        50.times do
            card = Card.create!(
                retailer: Faker::Company.name,
                category: category,
                offer_type: Faker::Company.buzzword,
                first_purchase: Faker::Company.industry,
                credit_limit: Faker::Number.between(10, 50) * 100,
                image: Faker::Placeholdit.image("100x50", 'jpg', :random))
            puts "Created card \"" + card.retailer + "\""
        end
    end
end

cards_controller.rb:

class CardsController < ApplicationController
    def index
        @cards = Card.all
        @cards = @cards.where(category_id: params[:category_id]) if params[:category_id]
    end

    def create
        card = Card.create!(card_params)
    end

    private
    def card_params
        params.require(:card).permit(:image, :retailer, :category, :offer_type, 
                                                                 :first_purchase, :credit_limit)
    end
end

cards.rb:

ActiveAdmin.register Card do
    permit_params :image, :retailer, :offer_type, :first_purchase, :credit_limit, :category_id

    form title: 'New Card' do |f|
      inputs 'Details' do
        input :retailer
        li "Created at #{f.object.created_at}" unless f.object.new_record?
        input :category
        input :offer_type
        input :first_purchase
        input :credit_limit
        input :image, as: :file
      end
      para "Press cancel to return to the list without saving."
      actions
    end

    show do
        attributes_table do
            row :retailer
            row "Image" do |card|
                image_tag url_for(card.image)           
            end
        end
    end

    index do
        column "Image" do |card|
            image_tag url_for(card.image), class: 'admin-image'         
        end
        column :retailer
        column :category
        column :offer_type
        column :first_purchase
        column :credit_limit
        actions
    end
end

0 个答案:

没有答案