4

I'm trying to save a photo into DB via AngularJS in Rails4. I used paperclip gem for the attachment setup

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_attached_file :photo, :styles => {:thumb => "100x100>"}
end

Here's my form:

<div ng-controller="RegistrationsController">
  <form ng-submit="saveUser()" name="signUpForm" novalidate>
    <input type="text" class="form-control" ng-model="user.email" ng-class="{submitted: submitted}" required />
    <input type="file" ng-model="user.photo" />
  </form>
</div>

Here's my angularJS Controller. In saveUser() function it will trigger the POST request. I've tried to output the value of $scope.user.photo but it's undefined according to browser console log.

myApp.controller "RegistrationsController", ($scope, $location, $http, $modal)->

  $scope.saveUser = () ->
    console.log $scope.user.photo
    $scope.submitted = true
    if $scope.signUpForm.$valid
        $http(
            url: "/api/users"
            method: "POST"
            data: $scope.user
        ).success((data) ->
            $scope.user = {}

            $location.path "/"
            return
        ).error (response) ->
            console.log(response)
            return

        return

I don't have idea on how to save/upload a single photo via AngularJS + Paperclip in Rails.

And on how the value will be saved.

Here's the controller for the create method:

class Api::V1::UsersController < ApplicationController
  def create
    @user = User.new(trusted_params)

    if @user.save
      UserMailer.welcome_email(@user).deliver!
      render json: @user
    else
      render json: {
        message: 'Validation failed', errors: @user.errors.full_messages
      }, status: 422
    end
  end

  private

    def trusted_params
      params.require(:user).permit(:first_name, :last_name, :email, :password, :photo)
    end
end

Any ideas will be appreciated. Thanks!

1
  • Did you get this working yet? Commented Aug 20, 2014 at 16:47

2 Answers 2

1

there is angular-file-upload provider, inject $upload to your controller and use ng-file-select directive, everything is on https://github.com/danialfarid/angular-file-upload

Sign up to request clarification or add additional context in comments.

Comments

0

have a look in the provided link, I have successfully implemented it.

Rails Example with paperclip

1 Comment

Hi am getting an error "Upload is not defined" . can you please help me on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.