ActiveAdmin - 有没有办法生成一个 CSV 结合两个属于父模型的模型? [英] ActiveAdmin - Is there a way to generate a CSV combining two models that belongs_to a parent one?
问题描述
我有一个模型 User
和 2 个模型,Foo
和 Bar
,belongs_to :user
.用户模型有 has_many :foo
和 has_many :bar
.
这些关联是在 rails
应用级别,而不是 active_admin
级别.
我想要的是从我已经拥有的用户显示页面生成一个 CSV,它结合了用户各自的 foo
和 bar
属性.>
Foo 和 Bar 共享一些属性,但不是全部,所以我知道有些字段会留空.
有没有办法在 Active Admin 中做到这一点?
我已经尝试使用 csv do
块,但无法将所有 Foo
和 Bar
放在同一块中.
您可以编写自己的 csv 生成代码.以下是一些可帮助您入门的脚手架代码:
sidebar :foos_bars_as_csv, :only =>[:show] 做a(href: foos_bars_as_csv_admin_user_path) 做'下载为 csv'结尾结尾member_action :foos_bars_as_csv, :method =>:做# 定义你自己的标题csv_headers = ["Header 1", "Header 2"] # 自定义foos = 资源.foos条 = 资源.条rawcsv = CSV.generate(:col_sep => ",") 做 |csv|# 在这里你可以添加标题# csv <<csv_headersfoos.each 做 |foo|csv< 'text/csv charset=utf-8; header=present', :filename => Time.now.strftime("%Y%m%e-%H%M%S) + 用户#{resource.id}-FoosnBars"并返回结尾
祝你好运!
I have a model User
, and 2 models, Foo
and Bar
that belongs_to :user
.
The user model have has_many :foo
and has_many :bar
.
These associations are in rails
app level, not active_admin
level.
What I want is to generate a CSV from the user show page, which I already have, that combines the respective foo
and bar
attributes of a user.
Foo and Bar share some attributes, but not all, so I'm aware that some fields will be left blank.
Is there a way to do this in Active Admin?
I've tried with the csv do
block but can't manage to get all the Foo
s and Bar
s inside the same csv.
You can write your own csv generation code. Here is some scaffolding code to get you started:
sidebar :foos_bars_as_csv, :only => [:show] do
a(href: foos_bars_as_csv_admin_user_path) do
'Download as csv'
end
end
member_action :foos_bars_as_csv, :method => :get do
# define your own headers
csv_headers = ["Header 1", "Header 2"] # customize yourself
foos = resource.foos
bars = resource.bars
rawcsv = CSV.generate(:col_sep => ",") do |csv|
# here you could add headers
# csv << csv_headers
foos.each do |foo|
csv << foo.build_csv_row # or something like this
end
bars.each do |bar|
bar << bar.build_csv_row
end
csv << csv_row
end
end
send_data(rawcsv, :type => 'text/csv charset=utf-8; header=present', :filename => Time.now.strftime("%Y%m%e-%H%M%S) + "User#{resource.id}-FoosnBars" and return
end
Good luck!
这篇关于ActiveAdmin - 有没有办法生成一个 CSV 结合两个属于父模型的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!