【发布时间】:2018-09-11 22:27:51
【问题描述】:
我正在尝试从我的 rails 应用程序的表中导出 CSV 文件。我可以导出 booking.attributes.values 并且可以单独导出 booking.user.attributes.values 但是当我尝试合并这两个时我收到一个错误。
“没有将Array隐式转换为Hash”
这是我正在使用的代码,包括一些注释代码。 csv 文件只提取了 booking.attributes 的标题。这是我需要弄清楚的额外内容。
预订模式
def self.to_csv(options = {})
# desired_columns = ["fname","lname","email","nationality","date_of_birth","phone_number"]
CSV.generate(options) do |csv|
csv << column_names
all.each do |booking|
# csv << booking.user.attributes.merge(booking.course.attributes).values_at(*desired_columns)
# csv << booking.user.attributes.values
# csv << booking.attributes.values
csv << booking.attributes.merge(booking.user.attributes.values).values
end
end
end
预订控制器
def index
@bookings = Booking.all.paginate(page: params[:page], per_page: 20)
# respond to look for html but also csv data and xls
respond_to do |format|
format.html
format.csv { send_data @bookings.to_csv }
format.xls
end
end
这是我尝试以 CSV 格式重新创建的表格视图。这按预期工作。
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Nationality</th>
<th scope="col">D.O.B</th>
<th scope="col">Phone Number</th>
<th scope="col">Course Name</th>
<th scope="col">Course Start</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody id="bookingTable">
<% @bookings.each do | booking | %>
<tr>
<td scope="row"><%= booking.user.fname %> <%= booking.user.lname %></td>
<td scope="row"><%= booking.user.email %></td>
<td scope="row"><%= booking.user.nationality %></td>
<td scope="row"><%= booking.user.date_of_birth&.strftime("%d/%m/%Y") %></td>
<td scope="row"><%= booking.user.phone_number %></td>
<td scope="row"><%= booking.course.title %></td>
<td scope="row"><%= booking.schedule.start_date&.strftime("%d %B %Y") %></td>
<td><%= link_to 'View User', user_path(booking.user), class: "btn btn-info" %></td>
</tr>
<% end %>
</tbody>
</table>
任何方向都将不胜感激。谢谢。
【问题讨论】:
标签: ruby csv ruby-on-rails-5