我正在尝试从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>任何方向都将不胜感激。谢谢。
发布于 2018-04-02 17:37:15
我认为您的问题是,您将预订的属性(散列)与预订用户的属性值(数组)不匹配。
因此,正如错误消息所显示的那样,计算机无法知道哪些值属于哪个键。
我猜你打算写:
booking.attributes.merge(booking.user.attributes).values
你的确写过:
booking.attributes.merge(booking.user.attributes.values).values
不管是什么情况,你要合并的东西都需要钥匙!
发布于 2018-04-02 18:11:08
CSV要求数组作为一行,而您正在处理散列:
# ⇓ hash ⇓ ⇓ hash ⇓ array ⇓ array ⇓
csv << booking.attributes.merge(booking.user.attributes.values).values 合并散列是危险的,因为如果user具有与booking相同的键,则后者将被丢弃。您想要的可能只是将两个值数组相加:
csv << (booking.attributes.values + booking.user.attributes.values)或者,如果用户的字段首先进入:
csv << (booking.user.attributes.values + booking.attributes.values)https://stackoverflow.com/questions/49615777
复制相似问题