Search code examples
javascriptruby-on-railsjsonajaxfilepicker

Save JavaScript Variable to Rails Model


I am using the FileStack API and the filepicker gem (https://github.com/Ink/filepicker-rails). I follow the steps outlined in the doc under Accessing FilePicker File with OnChange. I am attempting to grab the JSON browser response attribute, filename, pass it to my Rails controller via a route, and save it as a :name in my Attachment model.

Attachment/New view

<%= filepicker_js_include_tag %>

<%= simple_form_for(@attachment) do |f| %>

<%= f.filepicker_field :title, multiple: 'true', onchange: 'onUpload(event)' %>
<%= f.submit %>

<% end %>

<script>
  function onUpload(event) {
  var name = event.fpfile.filename;
  jQuery.ajax({
   data: { "attachment[name]": name, "attachment[title]": url },
   type: 'post',
   url: "/attachments"
  });
 }
</script>

Route

post 'attachments/' => 'attachment#create'

Attachment Controller

    def create

      @attachment = current_user.attachments.build(attachment_params)

      if @attachment.save
        redirect_to attachments_path
      else
        render root_path
      end
end
...

private

    def attachment_params
        params.require(:attachment).permit(:title, :user_id, :name)
    end

I have browsed the relevant SO posts which is how I came to this implementation. However when I view my Attachment model in the rails console, name is nil. My data isn't getting passed properly. I am not sure if I am missing a step or am not routing properly. Any advice would be much appreciated.


Solution

  • Your controller super messy delete most of them and just keep it simple as like below. That one line will cover for you current_user.id and name.

    def create
      @attachment = current_user.attachments.build(attachment_params)
      if @attachment.save
        redirect_to attachments_path
      else
        render root_path
      end
    end
    

    Also, meanwhile you have params permit

    params.require(:attachment).permit(:name, :title, :user_id)

    You have to pass data like this "attachment[name]", but you are passing it simple "name". Thats the reason getting Unpermitted parameter: name. And as @anonymousxxx mentioned remove :name part from routes!!!

    Script

    <script>
      function onUpload(event) {
      var name = event.fpfile.filename;
      jQuery.ajax({
       data: { "attachment[name]": name },
       type: 'post',
       url: "/attachments"
      });
     }
    </script>