Reputation: 776
i want to create a function into my controller to save a picture uploaded by an admin. I don't want to use plugin or Activerecord, just a function to write the bytes of the picture into the directory app/assets/images/ .
So , when the admin create a new product he puts the picture of the product into the app.
I want to use this function in the action create
of the Product Controller
.
In this way , before to save in the db the new product , the picture will be saved into the app (not in the db, i want just to write bytes).
I searched on internet and i founded a function to save picture.
I have a strange error : undefined method
read' for "picture.png":String`
Here all my things:
edit.html.erb
<h1>Editing product</h1>
<%= render 'form' ,:multipart => true%>
<%= link_to 'Show', @product %> |
<%= link_to 'Back', products_path %>
_form.html.erb
<%= form_for(@product) do |f| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :image_url %><br>
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :price %><br>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :upload %><br>
<%= file_field :upload, :datafile %></p>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
product_controller.rb
def create
name = params[:upload][:datafile]
directory = Rails.root.join('app', 'assets','images')
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(params[:upload][:datafile].read) }
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
thank you for the help.
EDIT: new error
Upvotes: 0
Views: 27
Reputation: 11570
Since you're using form_for
, the actual temp file will be in params[:product][:upload]
. Try this
Within the _form.html.erb
partial, change the file_field
line to
<%= file_field :upload %>
Then, within your create
action
name = params[:product][:upload].original_filename
directory = Rails.root.join('app', 'assets','images')
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(params[:product][:upload].read) }
Upvotes: 1