Ruby on Rails - export user data to csv - button

℡╲_俬逩灬. 提交于 2019-12-24 09:59:14

问题


Since I ended up using a csv method and not a json method I thought it might be a good Idea to change the question name and remove the part with the json if other people might have the same problem someday.

Update: I've tried using this as a way to export data.

In my controller I have the following:

def profile
@user = User.find(params[:id])
@user_posts = @user.posts.order('created_at DESC')

respond_to do |format|
  format.html
  format.csv { send_data @user.csv, filename: "userinfo-#{Date.today}.csv" }
end

end

In my view :

<p><%= link_to("Generate Report", user_path(@user, format: :csv), class: "btn btn-success",) %></p>

In my user.rb :

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

Update 2: Managed to fix it myself, I was using a wrong csv method in my Controller. Replacing it with the following :

def csv
    CSV.generate do |csv|
      csv << %w{ user_id user_username user_email }
      csv << [ self.id, self.username, self.email]
    end
  end

works like a charm.

Best regards

来源:https://stackoverflow.com/questions/51566784/ruby-on-rails-export-user-data-to-csv-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!