显示照片预览,但照片未保存在表单中:使用Carrierwave和JS预览照片

时间:2016-12-28 14:39:08

标签: javascript ruby-on-rails ruby carrierwave image-uploading

我试图通过(编辑)-form更新用户的个人资料图片。我想向用户显示它要上传的照片,因此我使用JS预览所选照片。问题是预览正在显示,但新照片未通过表单保存。

关于我可能错过的任何想法?

edit.html.erb

<%= f.inputs do %>
 <% if @user.photo? %>
  <div id="photo_edit">
    <img id="img_prev" class="profile_photo_edit" src="<%= current_user.photo %>">
     <label id="photo-edit-button">
      <input type='file' onchange="readURL(this);" />
      <%= f.file_field :photo %>
      <%= f.hidden_field :photo_cache %>
      <span>Wijzig foto</span>
     </label>
  </div>
 <% else %>
  <div id="photo_edit">
   <%= image_tag "PICA.jpg", :id => "img_prev", :class => "profile_photo_edit"%>
    <label id="photo-edit-button">
     <input type='file' onchange="readURL(this);" />
     <%= f.file_field :photo %>
     <%= f.hidden_field :photo_cache %>
     <span>Wijzig foto</span>
    </label>
   </div>
<% end %>

photo-preview.js

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

      reader.onload = function (e) {
        $('#img_prev')
        .attr('src', e.target.result)
        .width(100)
        .height(100);
      };

        reader.readAsDataURL(input.files[0]);
      }
    }

users_controller.rb

    class Profile::UsersController < ApplicationController
      skip_before_filter :verify_authenticity_token
      before_action :correct_user,   only: [:edit, :update]


      def index

      # pagination
      @users = User.order(:name)

      query = params[:search].presence || "*"
      @results = User.search params[:search], page: params[:page], per_page: 9

      # @results = User.search params[:search], where: {id: {not:         current_user.id}}
    end


    def create
      @user = User.new(user_params)

      if @user.save
        redirect_to :action => 'show'
      else
        render :action => 'edit'
      end
    end

    def new
      @user = current_user
    end

    def show
      @user = User.find(params[:id])
      map
      @competences = @user.competences.all
    end

    def edit
      @user = User.find(params[:id])
      @profiles = Profile.all
      @locations = Location.all
      @positions = Position.all
      @competences = Competence.all
    end

    def update
      @user = User.find(params[:id])

      if @user.update_attributes(user_params)

        print "--------"
        @bla = []
        @usercompetence = @user.competences

          # Insert / add expertises
          for competence in params[:expertises]
            print competence

            if competence.blank?
              next
            end

            print "\n"
            comp_object = nil

            if Competence.exists?(id: competence)
              comp_object = Competence.find(competence)
            elsif Competence.exists?(name: competence, user_id: current_user.id)
              comp_object = Competence.where(name: competence, user_id: current_user.id).first()
            else
              comp_object = Competence.new(name: competence, user_id: current_user.id, category: "expertise")
              comp_object.save
            end

            print "adding..."
            print comp_object[:name]
            print comp_object[:category]
            print "\n"
            @bla << comp_object

            unless @usercompetence.include?(comp_object)
              @usercompetence << comp_object
            end
          end

          # Insert / add expertises
          for competence in params[:competenties]
            print competence

            if competence.blank?
              next
            end

            print "\n"
            comp_object = nil

            if Competence.exists?(id: competence)
              comp_object = Competence.find(competence)
            elsif Competence.exists?(name: competence, user_id: current_user.id)
              comp_object = Competence.where(name: competence, user_id: current_user.id).first()
            else
              comp_object = Competence.new(name: competence, user_id: current_user.id, category: "competence")
              comp_object.save
            end

            print "adding..."
            print comp_object[:name]
            print comp_object[:category]
            print "\n"
            @bla << comp_object

            unless @usercompetence.include?(comp_object)
              @usercompetence << comp_object
            end
          end

          # Delete competences from user
          print "--------"
          for competence in @usercompetence
            print "Checking.."
            print competence[:name]
            unless @bla.include?(competence)
              print "Delete..."
              @usercompetence.delete(competence)
            end
          end
          print "-------------"

          @user.save

          redirect_to :action => 'show'

        end
      end

      def destroy
        Profile.find(params[:id]).destroy
        redirect_to :action => 'new'
      end

      private

      def user_params
        params.require(:user).permit(:first_name, :last_name, :current_position, :position_description, :email, :phonenumber, :linkedin, :skype, :location_id, :location_specs, :photo, :photo_cache)
      end


      def map
        @user = User.find(params[:id])
        if @user.location_id
          @location = Location.find(@user.location_id)
        end
        @hash = Gmaps4rails.build_markers(@location) do |location, marker|
          marker.lat location.latitude
          marker.lng location.longitude
        end
      end

      def correct_user
        @user = User.find(params[:id])
        redirect_to(root_url) unless @user == current_user
      end

    end

user.rb

    class User < ApplicationRecord
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
      :recoverable, :rememberable, :trackable, :validatable

      mount_uploader :photo, PhotoUploader

      searchkick
      paginates_per 6

      before_save :generate_competence?

      belongs_to :location
      has_one :profile, dependent: :destroy
      has_and_belongs_to_many :competences

      def search_data
        attributes.merge(
          competence_name: competences.map(&:name),
          location_name: location(&:name)
          )
      end
    end

0 个答案:

没有答案