Rails如何只下载当前记录点击下载按钮
我是新来的铁轨。我正在开发一个包含添加客户的应用程序。在那里我有下载按钮。当我点击下载按钮时它应该在csv文件中下载当前客户页面。Rails如何只下载当前记录点击下载按钮
控制器
def create
@customer_detail = CustomerDetail.new(customer_detail_params)
@customer_detail.company_profile_id = current_user.company_profile.id
respond_to do |format|
if @customer_detail.save
format.html { redirect_to edit_customer_detail_path(@customer_detail), notice: 'customerDetails was successfully created.' }
# format.html { render 'edit', notice: 'customerDetails was successfully created.' }
else
format.html { render :new }
end
end
end
def index
@customer_details = CustomerDetail.all
end
def destroy
end
def update
respond_to do |format|
format.html
format.csv { render text: @customer_details.to_csv }
if @customer_detail.update(customer_detail_params)
format.html { redirect_to @customer_detail, notice: 'customer_details was successfully updated.' }
else
format.html { render :edit }
end
end
end
查看
.fieldset
.row
.col-sm-3
= f.submit "Save", class: "btn btn-primary"
.col-sm-3
= f.submit "cancel", type: :reset, class: "btn btn-primary"
.col-sm-3
= link_to "Download", edit_customer_detail(format: "csv"), class: "btn btn-primary"
.col-sm-3
= link_to("Print", "javascript:print()", class: "btn btn-primary")
问题是,它从下载的形式的所有记录。我不知道是否要更新或编辑行动。如果我给路径edit_customer_detail而不是customer_details_(路径)它显示模板错误,并单击下载按钮时没有路径匹配错误。有人请帮助我。我是在这里附上输出链接。提前致谢!!
模型
def to_csv
CSV.generate do |csv|
csv << self.class.column_names
csv << self.attributes.values_at(*self.class.column_names)
end
end
控制器
def download_csv
respond_to do |format|
format.html
format.csv { render text: @customer_detail.to_csv }
end
end
视图
.col-sm-3
- if @customer_detail.save
= link_to "Download", download_csv_customer_detail_path(@customer_detail.id, format: "csv"), class: "btn btn-primary"
在控制器的更新方法,下面一行变化:
format.csv { render text: @customer_details.to_csv } with
format.csv { render text: @customer_detail.to_csv }
在application.rb中 添加require 'csv'
更改您的更新功能
def update
respond_to do |format|
format.html
format.csv { render text: @customer_detail.to_csv }
if @customer_detail.update(customer_detail_params)
format.html { redirect_to @customer_detail, notice: 'customer_details was successfully updated.' }
else
format.html { render :edit }
end
end
你是道琼斯为所有用户下载报告,因为@customer_details = CustomerDetail.all
会为所有用户返回数据。
我已经添加了require'csv'。所以它下载,但不是当前的用户form.It下载所有用户records.It显示我的模板是缺少错误,如果我给customer_details_path。如果我给edit_customer_detail,没有路线匹配。谢谢!。你能进一步帮助我吗? –
@HariPrakash您没有edit_customer的匹配路由:/customers/:id/edit(.:format)customers#edit。你可以创建一个功能和路线来编辑客户的详细信息 –
改变!。它表明了我的模板丢失的错误,如果我给customer_details_path。如果我给edit_customer_detail,没有路线匹配。你能进一步帮助我吗? –
= link_to“下载”,customer_details_path(格式:“csv”),类:“btn btn-primary” –
我必须在我的代码中替换?.in表单?或控制器?你可以详细解释一下 –