简体   繁体   中英

undefined method `to_csv' Rails 5

I'm trying to use .to_csv for the first time, and I'm receiving the error undefined method 'to_csv' for #<Datum::ActiveRecord_Relation:0x007fd101f32f08> Did you mean? to_s undefined method 'to_csv' for #<Datum::ActiveRecord_Relation:0x007fd101f32f08> Did you mean? to_s

I've looked around, and I'm unsure if it's my code or .to_csv is incompatible with Rails 5 (5.0.6 to be exact)? Then end goal is for the user to download all the Datum data on the current Batch show page.

Any pointers would be great!

application.rb

require File.expand_path('../boot', __FILE__)
require 'csv'
require 'uri'
require 'net/http'
require 'rails/all'

models/batch.rb

class Batch < ApplicationRecord
  belongs_to :user


  def self.to_csv
    CSV.generate do |csv|
      csv << column_names
      all.each do |datum|
        csv << datum.attributes.values_at(*column_names)
      end
    end
  end
end

batches_controller.rb

def show
   batch_id = params[:id]
   @batch_name = Batch.find(batch_id).name
   @data = Datum.where(batch_id: batch_id)

  respond_to do |format|
    format.html
    format.csv { send_data @data.to_csv }
  end
end

views/batches/show.html.erb

<%= link_to "CSV", batch_path(@batch, format: "csv") %> 

I don't know if could be helpfull but have you tried to create a show.csv.erb in you app/views/batchs/ folder?

EDIT:

I notice you define to_csv method on another class. I can suppose Datum has a relation one_to_many with Batch, if my considerations are correct try this

models/batch.rb

class Batch < ApplicationRecord
  belongs_to :user
  has_many :datums

  def self.to_csv
    CSV.generate do |csv|
      csv << column_names
      all.each do |datum|
        csv << datum.attributes.values_at(*column_names)
      end
    end
  end
end

batches_controller.rb

def show
   @batch = Batch.find(batch_id)

  respond_to do |format|
    format.html
    format.csv { send_data @batch.to_csv }
  end
end

You can always retrieve name by @batch.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM