I'm trying to create a dropzone where users can drop multiple files at once. The problem is that it only renders the dropzone when I reload the webpage, and not when I open it for the first time. I mean, when I click to open the view that takes care of the uploads, I just get the browse and upload buttons that you'll see in my code, but when I reload the page I get the dropzone box. I can not see what I missing here. The code I wrote was:
_new.html.erb
<center>
<% #upload = Upload.new %>
<%= form_for #upload , html: { :multipart => true, class: "dropzone"} do |u| %>
<div class="fallback">
<%= u.file_field :file %><br>
<%= u.submit "Upload" %>
</div>
<% end %>
uploads.js.coffee
$(document).ready () ->
Dropzone.autoDiscover = false;
$("#new_upload").dropzone({
maxFilesize: 25,
paramName: "upload[file]",
addRemoveLinks: true
});
uploads_controller.rb
class UploadsController < ApplicationController
def new
#upload = Upload.new
end
def create
#upload = Upload.create(upload_params)
if #upload.save
render json: { message: "success" }, :status => 200
else
render json: { error: #upload.errors.full_messages.join(',')}, :status => 400
end
end
def destroy
#upload = Upload.find(params[:id])
if #upload.destroy
render json: { message: "Archivo eliminado." }
else
render json: { message: #upload.errors.full_messages.join(',') }
end
end
private
def upload_params
user = current_user.id
params.require(:upload).permit(:file,:user)
end
end
You could also notice that in the _new.html.erb file I'm redefining the #upload class variable, that was already defined in the controller. If I remove it the new action won't work. What's the problem there?
Please ask me if you need me to provide more code or details.
Thanks in advanced.
You should add 'data-no-turbolink': true to the link that opens that page. Turbolinks doesn't always play nice with $(document).ready so this will call the link without turbo links.
There is also a gem called jquery-turbolinks that might make the current version work without data-no-turbolink
Related
I'm having a routing issue with an image. In my app I have images of items on the home page. I would like them to link to their image page.
Here is what my items controller looks like:
class ItemsController < ApplicationController
def show
#item = Item.find(params[:id])
end
end
This is what I have in my routes:
Rails.application.routes.draw do
resources :items
end
And this is what I have in the item partial:
<%= link_to(image_tag(item.image.url(:thumb)), item_path(:id)) %>
What I expected after reading the rails routing guide was that this would link to the item page for that image. Here is their example:
photo_path(:id) returns /photos/:id (for instance, photo_path(10) returns /photos/10)
I should also add that this is in my home page controller:
class StaticPagesController < ApplicationController
def home
#items = Item.where.not(category_id: 1)
end
However, that is not working. I've tried several different things, but all produce errors. Is there a simple way to do this?
The normal way to do what you want is this:
<%= link_to item_path(item) do %>
<%= image_tag(item.image.url(:thumb)) %>
<% end %>
You can just pass the instance of the item to item_path and also if you have complicated html for a link, it is usual to put it in a block for the link as shown here (with link_to something do).
I am facing a strange issue.
I have Post has_many attachments. as: :imageable
and
Attachment belongs_to imageable, polymorphic: true
I am trying to upload multiple images attached to a single post using dropzone.js
However, whenever I upload multiple files in the dropzone-powered form, each image gets uploaded as its own post. I upload 4 images, I get 4 posts with each of the attached image.
How can I get all of the images I attach to a post to be associated with that post only?
Here is what the posts.js looks like:
$(document).ready(function(){
// disable auto discover
Dropzone.autoDiscover = false;
// grap our upload form by its id
$("#new_post").dropzone({
// restrict image size to a maximum 1MB
maxFilesize: 1,
// changed the passed param to one accepted by
// our rails app
paramName: "post[attachments_attributes][][picture]",
// show remove links on each image upload
addRemoveLinks: true
});
});
Create action from the PostsController
def create
#post = Post.create(post_params)
if #post.save
render json: { message: "success" }, :status => 200
else
# you need to send an error header, otherwise Dropzone
# will not interpret the response as an error:
render json: { error: #post.errors.full_messages.join(',')}, :status => 400
end
end
Relevant section of the _form.html.erb for the new Post action:
<%= form_for(#post, html: {class:"dropzone"}) do |f| %>
....
<div class="fallback">
<%= f.label :attachments %>
<%= f.fields_for :attachments do |at| %>
<%= at.file_field :picture %>
<% end %>
</div>
....
<% end %>
The param name is post[attachment_attributes][0][picture] as it appears in the form HTML.
I suspect that this is the cause for the issue, but how do I change it so that the request uploads all the images attached to one post?
Thanks in advance!
Dropzone Issue It looks like this is an issue that is untested but you can use the development branch of Dropzone to access it. This link has the details.
In my app I have Issue model, which belongs_to Status model. What I need to do is to have dropdown list of links (or spans, doesn't matter) with Statuses Id's on Issue show page, so I could change status clicking on this (could be non-ajax and ajax).
I am rather new to Rails, so I do not know how to implement this, was thinking of few ways to do this, but non seems to be working.
Because you're new, I'll outline what I'd do for you (hopefully it will help):
#config/routes.rb
resources :issues do
get "change_status/:status_id", to: "issues#change_status"
end
#app/models/status.rb
Class Status < ActiveRecord::Base
has_many :issues
scope :not, ->(id) { where('statuses.id != ?', id) }
end
#app/controllers/issues_controller.rb
def show
#issue = Issue.find params[:id]
#statuses = Status.all.not(#issue.id)
end
def change_status
issue = Issue.find params[:id]
issue.status = params[:status_id]
issue.save if issue.status_id_changed?
redirect_to issue
end
#app/views/issues/show.html.erb
<%= #statuses.each do |status| %>
<%= link_to status.title, issue_change_status_path(#issue, status) %>
<% end %>
There's obviously some stuff to explain - if you need me to do that, let me know and I'll give you the details!
You can simply use the link_to rails helper like in the following code:
link_to "Change Status", my_path_to_update_status, remote: true, method: :put
This will send an AJAX PUT request (thank to the remote: true) to your my_path_to_update_status.
Then, you just have to update the status in the action corresponding to the path specified in the link_to helper tag.
More information about the link_to rails helper here
I've been trying like crazy to work through this permit error using some of the other StackOverflow postings, but can't seem to get past it. I've got a projects model & controller & a versions model & controller. Projects/##/versions/new is a form page to create a new version of project id ##. But when I click the submit button to create the version...it throws the following error in the VersionsController:
undefined method `permit' for "Submit Now! ":String
Extracted source (around line #36):
34
35
36
37
38
def version_params
params.require(:version).permit(:title)
end
end
Any and all help would be greatly appreciated...I've been trying to fix this for too long now. My Code is as follows:
ROUTES.RB
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :projects, only: [:create, :new, :show, :edit, :update, :destroy]
resources :projects do
resources :versions
end
# get "static_pages/home"
# get "static_pages/help"
# get "static_pages/about"
#The original routes above map to...
root 'static_pages#home'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
match '/help', to: 'static_pages#help', via: 'get'
match '/about', to: 'static_pages#about', via: 'get'
match '/contact', to: 'static_pages#contact', via: 'get'
PROJECTS MODEL:
class Project < ActiveRecord::Base
has_many :users
has_many :versions, dependent: :destroy
validates :title, presence: true, length: { maximum: 100 }
validates :background, presence: true
validates :user_id, presence: true
default_scope -> { order('created_at DESC') }
end
VERSIONS MODEL:
class Version < ActiveRecord::Base
belongs_to :project
validates :title, presence: true, length: { maximum: 140 }
default_scope -> { order('created_at DESC') }
end
VERSIONS CONTROLLER:
class VersionsController < ApplicationController
def new
#version = Version.new
end
def show
#project = Project.find(params[:project_id])
#version = Version.find(params[:id])
end
def index
#versions = Version.paginate(page: params[:page])
end
def create
#project = Project.find(params[:project_id])
#version = #project.versions.create(version_params)
if #version.save
flash[:success] = "You've successfully added a version to this branch..."
redirect_to project_path(#project)
else
render 'new'
end
end
def edit
end
def update
end
def destroy
end
private
def version_params
params.require(:version).permit(:title)
end
end
NEW.HTML.ERB (new version form):
<% provide(:title, 'New Version') %>
<h1>Add a version to this project</h1>
<div class="row-fluid">
<div class="col-md-5 no-pad offset3">
<%= bootstrap_form_for #version, :url => project_versions_path do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :title %>
<br clear="all">
<%= f.submit "Submit Now! ", class: "btn btn-lg btn-primary" %>
<% end %>
</div>
</div>
PARAMS:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"submit"=>"Submit Now! ",
"project_id"=>"51"}
Processing by VersionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"################=", "version"=>"Submit Now! ", "project_id"=>"51"}
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? ORDER BY created_at DESC LIMIT 1 [["id", "51"]]
Completed 500 Internal Server Error in 3ms
NoMethodError (undefined method `permit' for "Submit Now! ":String):
app/controllers/versions_controller.rb:41:in `version_params'
app/controllers/versions_controller.rb:17:in `create'
I can recognize the problem in the params. You have this:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"submit"=>"Submit Now! ",
"project_id"=>"51"}
You should have this:
{"utf8"=>"✓",
"authenticity_token"=>"######AAAA",
"project_id"=>"51",
"version"=>{"title"=>"Foo Bar"},
"button"=>""}
The reason this is a problem is because you do not have a version title being passed in the params, and you are trying to create a new version with the params. It instead looks for the closest thing which in this case happens to be the string "Submit Now!", but since "submit" is not permitted than strong params tosses it out.
It looks like you are creating your form correctly, it may be an issue with bootstrap_form_for. Can you post what the input output for title looks like in html on your form?
In the meantime I have two suggestions,
First thing that may solve the problem, is to change f.submit to f.button.
f.button will still create a submit button, but it allows you to name is in the way that you are trying to.
Also in the controller, you don't need to save after you call create. create will actually store it in the database, so you are saving it twice. You should either call new instead of create
#version = #project.versions.new(version_params)
if #version.save
of check if new record
#version = #project.versions.create(version_params)
unless #version.new_record?
I'm trying to access my page gallery/new via a link, so i have created this
<%= link_to 'New gallery' new_gallery_path %>
rake routes gives
gallery_index_path GET /gallery(.:format) gallery#index
POST /gallery(.:format) gallery#create
new_gallery_path GET /gallery/new(.:format) gallery#new
edit_gallery_path GET /gallery/:id/edit(.:format) gallery#edit
gallery_path GET /gallery/:id(.:format) gallery#show
PATCH /gallery/:id(.:format) gallery#update
PUT /gallery/:id(.:format) gallery#update
DELETE /gallery/:id(.:format) gallery#destroy
and within my routes i have
resources :gallery
My view at gallery/new is
<%= nested_form_for #gallery, :html => { :multipart => true} do |f| %>
--content here
<% end %>
whenever i click the link to view this page i get
undefined method `galleries_path
Can someone point out my mistake, please?
You've chosen the wrong name for your resources. It should always be pluralized:
resources :galleries
From this Rails will generate the plural and singular paths correctly. galleries_path for the index, gallery_path for show, etc etc.