我不太确定,当我试图让csv下载我的游戏模型时,我忽略了什么,我有点迷路了。
在配置文件显示页面上,我呈现一个类似于与该用户关联的游戏列表的索引,即他们的游戏时间表。
Profiles控制器-
def show
@user = User.find_by_profile_name(params[:id])
if @user
@listings = @user.listings
@games = @user.games
respond_to do |format|
format.html
format.csv {send_data @games.to_csv}
end
return
render action: :show
else
render file: "public/404", status: 404, formats: [:html]
end
end然后在game.rb中定义to_csv方法
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |item|
csv << item.attributes.values_at(*column_name)
end
end
end并在配置文件显示页面上下载预期的csv游戏时间表。
<%= link_to "Download my Schedule", profile_path(format: 'csv')%>我相信这可能是我的问题,但这并不能解释我在csv中得到了什么,因为csv只是一个游戏对象。
档案-

这是我的routes.rb
resources :games
match 'friendships/:friend_id' => 'user_friendships#new', :as => :new_friendship
match 'dashboard' => 'dashboard#show', :as => :dashboard
root to: "profiles#index"
get '/players', to: 'profiles#index', as:'players'
get '/players', to: 'profiles#index', as:'users'
get '/:id', to: "profiles#show", as: 'profile'文件的格式应以列名(位置、对手、时间等)作为标题行,并为每个与用户关联的实例设置相应的行及其各自的值。
发布于 2013-12-22 23:50:06
我认为to_csv方法在游戏中应该重新声明为-
values_at的param是column_names而不是column_name。
def self.to_csv(游戏) CSV.generate do csv _ csv << csv column_names games.each do \csv << item.attributes.values_at(*column_names)末端在控制器中,代码应该是:
def show
@user = User.find_by_profile_name(params[:id])
if @user
@listings = @user.listings
@games = @user.games
respond_to do |format|
format.html
format.csv {send_data Game.to_csv(@games)}
end
return
render action: :show
else
render file: "public/404", status: 404, formats: [:html]
end
end否则,不管您使用的是哪个用户,您都会输出所有游戏。
发布于 2013-12-23 10:22:06
虽然森琼格的回答并没有错,但让我详细说明一下。
语法Game.to_csv(@games)违背了Rails的面向对象方法。
因为在您的情况下,CSV生成代码完全独立于模型(您不对列名进行任何假设,等等)您可以为该方法提供任何模型数组,即Game.to_csv(@shampoos),它仍然可以工作,但读起来不太好。
由于Rails method根据附加到ActiveRelation对象的条件,在类方法中使用它不会导致所有游戏的输出。
假设您至少使用了Rails 3.0,那么行@games = @user.games将为您提供一个ActiveRelation对象,而不是数组,这意味着您可以直接调用@games.to_csv (或使其更加清晰),从而读取它是什么,即将属于用户的游戏列表转换为CSV。
哦,我想这只是测试代码,但是return不应该在那里。render语句应该进入format.html块。
https://stackoverflow.com/questions/20735163
复制相似问题