This is my working! model view and controller (without AJAX):
Model: attachment.rb
class Attachment < ActiveRecord::Base belongs_to :task belongs_to :user validates_presence_of :comment
def uploaded_file=(file_field) self.name = base_part_of(file_field.original_filename) self.content_type = file_field.content_type.chomp self.data = file_field.read end
def base_part_of(file_name) File.basename(file_name).gsub(/[^\w._-]/, '' ) end end
View:
<% form_for(:attachment, :url => {:controller => 'attachment', :action => 'save', :task_id => params[:id]}, :html => { :multipart => true }) do |form| %> Upload your file: <br /> <%= form.file_field(:uploaded_file) %><br/> Comment: <br /> <%= form.text_field(:comment) %> <br /> <%= submit_tag("Upload file" ) %> <% end %>
Controller#save:
def save params[:attachment][:user_id] = current_user.id params[:attachment][:task_id] = params[:task_id] @attach = Attachment.new(params[:attachment]) if @attach.save flash[:notice] = "New attachment added" else flash[:notice] = "There were problems" end redirect_to(:controller => 'tasks' , :action => 'edit' , :id => params[:task_id]) end
And this is not working! controller and view with AJAX (model is the same):
Controller#add_new:
def add_new @task = Task.find_by_id(params[:id]) params[:attachment][:user_id] = current_user.id params[:attachment][:task_id] = params[:task_id] @attach = Attachment.new(params[:attachment]) if @attach.save @attach = @task.attachments end render :partial => "./tasks/ajax_attachments" end
View:
<% remote_form_for(:attachment, :before => "Element.show('spinner')", :success => "Element.hide('spinner')", :url => { :controller => 'attachment', :action => 'add_new', :task_id => @task }, :update => 'atte', :html => { :multipart => true }) do |form| %> Upload your file: <br /> <%= form.file_field(:uploaded_file) %><br/> Comment: <br /> <%= form.text_field(:comment) %> <br /> <%= submit_tag("Upload file" ) %> <% end %>
When I use ajax this code doesn't work and error appears like that:
undefined method `original_filename' for "E:\\article.txt":String
and ApplicationTrace
#{RAILS_ROOT}/app/models/attachment.rb:7:in `uploaded_file=' #{RAILS_ROOT}/app/controllers/attachment_controller.rb:25:in `new' #{RAILS_ROOT}/app/controllers/attachment_controller.rb:25:in `add_new' -e:4:in `load' -e:4
How can I fixed It???