Reputation: 207
after my user uploads a file and hits "submit" i would like to alert them that the upload was successful. But nothing happens when I do.
Here is in the controller:
def create
# make a new picture with what picture_params returns (which is a method we're calling)
@picture = Picture.new(picture_params)
if @picture.save
# if the save for the picture was successful, go to index.html.erb
redirect_to pictures_url
flash[:alert] = "Upload successful!"
else
# otherwise render the view associated with the action :new (i.e. new.html.erb)
render :new
end
end
Form:
<container>
<center>
<%= form_for @picture do |f| %>
<input type="file" multiple> <%= f.file_field :picture %>
<p>Drag your files here or click in this area.</p>
<button type="submit"> <%= f.submit "Save" %> Upload </button>
<% if flash[:alert] %>
<div class="alert"><%= flash[:alert] %></div>
<% end %>
</form>
<% end %>
</container>
Thanks!
Upvotes: 0
Views: 243
Reputation: 6418
Your create method should be like this:
def create
@picture = Picture.new(picture_params)
if @picture.save
flash[:alert] = "Upload successful!"
redirect_to pictures_url
else
render :new
end
end
The redirect should be after the flash. You can also do it like this:
redirect_to pictures_url, alert: "Upload successful!"
And the div
you are creating for flash message should be on the index page of pictures i.e., the page you are redirecting to and not in the form itself.
Hope this helps.
Upvotes: 1