我正在尝试在我的Rails应用程序中添加上传和下载文件的选项,但是当我尝试上传文件时,我一直收到此错误:
name can't be blank
这是我的代码:
newsletters_controller.rb:
class NewslettersController < ApplicationController
def index
@newsletters = Newsletter.all
end
def new
@newsletter = Newsletter.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @newsletter }
end
end
def create
@newsletter = Newsletter.new(newsletter_params)
if @newsletter.save
redirect_to newsletters_path, notice: "The newsletter #{@newsletter.name} has been uploaded."
else
render "new"
end
end
def destroy
@newsletter = Newsletter.find(params[:id])
@newsletter.destroy
redirect_to newsletters_path, notice: "The newsletter #{@newsletter.name} has been deleted."
end
private
def newsletter_params
params.require(:newsletter).permit(:newsletter, :attachment)
end
end
index.html.erb:
<% if !flash[:notice].blank? %>
<div class="alert alert-info">
<%= flash[:notice] %>
</div>
<% end %>
<br />
<%= link_to "New Newsletter", new_newsletter_path, class: "btn btn-primary" %>
<br />
<br />
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Download Link</th>
<th> </th>
</tr>
</thead>
<tbody>
<% @newsletters.each do |newsletter| %>
<tr>
<td><%= newsletter.name %></td>
<td><%= link_to "Download Newsletter", newsletter.attachment_url %></td>
<td><%= button_to "Delete", newsletter, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{newsletter.name}?" %></td>
</tr>
<% end %>
</tbody>
</table>
new.html.erb:
<% if !@newsletter.errors.empty? %>
<div class="alert alert-error">
<ul>
<% @newsletter.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="well">
<%= form_for @newsletter, html: { multipart: true } do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :attachment %>
<%= f.file_field :attachment %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
</div>
routes.rb中:
resources :newsletters, only: [:index, :new, :create, :destroy]
root "newsletters#index"
get "newsletters/index"
get "newsletters/new"
get "newsletters/create"
get "newsletters/destroy"
答案 0 :(得分:0)
变化:
params.require(:newsletter).permit(:newsletter, :attachment)
为:
params.require(:newsletter).permit(:newsletter, :attachment, :name)
这样,模型将从表单中接收名称,验证将成功。