0

error

Error while uploading the image

I'm unable to upload an image in my nested scaffold form.

All other fields are getting in the database except the image. Please help!

I am on rails 5.2 and using paperclip for image uploading and images need to be uploaded on AWS.

I am not getting any errors its just the images are not entering the database.

Thanks!

Form Partial

    <div class="panel panel-default">
  <div class="panel-heading">
    <span><i class="fa fa-bolt" style="color: #ffb400"></i> Apply for this campaign</span>
  </div>
  <div class="panel-body">

<%= form_for([@campaign, @campaign.contents.new]) do |f| %>
<div class="row">
  <div class="col-md-12">
    <label>Post Copy</label>
    <%= f.text_area :post_copy, rows: 5, placeholder: "Create your post exactly as you'd like to see it published.", class: "form-control", required: true %>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <label>Price USD</label>
    <%= f.text_field :price, placeholder: "How much you will charge", class: "form-control", required: true %>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <span class="btn btn-default btn-file text-babu">
      <i class="fa fa-cloud-upload" aria-hidden="true"></i> Select Photos
      <%= f.file_field "image[]", type: :file, multiple: true %>
    </span>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <label>Where will you post?</label>
  </div>

  <% if [email protected]? %>
  <div class="col-md-3">
    <%= f.check_box :is_facebook %> Facebook
  </div>
  <% end %>

  <% if [email protected]? %>
  <div class="col-md-3">
    <%= f.check_box :is_twitter %> Twitter
  </div>
  <% end %>

  <% if [email protected]? %>
  <div class="col-md-3">
    <%= f.check_box :is_instagram %> Instagram
  </div>
  <% end %>

  <% if [email protected]? %>
  <div class="col-md-3">
    <%= f.check_box :is_youtube %> Youtube
  </div>
  <% end %>
</div>

<br/>
<%= f.submit "Submit for Approval", class: "btn btn-normal btn-block" %>
<% end %>
</div>
</div>

Controller

class ContentsController < ApplicationController
  before_action :set_campaign, except: [:your_posts]
  before_action :set_content, only: [:show, :edit, :update, :destroy, :approve, :decline]

  # GET campaigns/1/contents
  def index
    @contents = @campaign.contents
  end

  # GET campaigns/1/contents/1
  def show
  end

  # GET campaigns/1/contents/new
  def new
    @content = @campaign.contents.build
  end

  # GET campaigns/1/contents/1/edit
  def edit
  end

  # POST campaigns/1/contents
  def create
    if !current_user.is_active_influencer
      return redirect_to payout_method_path, alert: "Please Connect to Stripe Express first."
    end

    campaign = Campaign.find(params[:campaign_id])
    if campaign.active == false
      flash[:alert] = "This Campaign is closed"
    elsif current_user == campaign.user
      flash[:alert] = "You cannot apply for your own campaign!"
    elsif
      @content = current_user.contents.build(content_params)
      @content.campaign = campaign
      @content.transaction_fee = @content.price * 15/100
      @content.total = @content.price + @content.transaction_fee
      @content.save

      flash[:notice] = "Applied Successfully!"
    end
    redirect_to campaign
  end

  # PUT campaigns/1/contents/1
  def update
    if @content.update_attributes(content_params)
      redirect_to([@content.campaign, @content], notice: 'Content was successfully updated.')
    else
      render action: 'edit'
    end
  end

  # DELETE campaigns/1/contents/1
  def destroy
    @content.destroy
    redirect_to campaign_contents_url(@campaign)
  end

  def your_posts
    @posts = current_user.contents
  end

  def approve
    if current_user.stripe_id.blank?
      flash[:alert] = "Please update your payment method."
      return redirect_to payment_method_path
    elsif
      charge(@campaign, @content)
    elsif
      flash[:alert] = "Cannot make a reservation!"
    end
  end

  def decline
    @content.Declined!
    redirect_to campaign_contents_path
  end

  private

  #Twilio_start
  def send_sms(campaign, content)
    @client = Twilio::REST::Client.new
    @client.messages.create(
      from: '+18646060816',
      to: content.user.phone_number,
      body: "You content for '#{campaign.brand_name}' has been approved."
    )
  end
  #Twilio_end

  def charge(campaign, content)
    if !campaign.user.stripe_id.blank?
      customer = Stripe::Customer.retrieve(campaign.user.stripe_id)
      charge = Stripe::Charge.create(
        :customer => customer.id,
        :amount => content.total * 100,
        :description => campaign.name,
        :currency => "usd",
        :destination => {
          :amount => content.price * 95, # 95% of the content amount goes to the Content Maker
          :account => content.user.merchant_id # Influencer's Stripe customer ID
        }
      )

      if charge
        content.Approved!
        ContentMailer.send_email_to_influencer(content.user, campaign).deliver_later if content.user.setting.enable_email
        send_sms(campaign, content) if content.user.setting.enable_sms #Twilio
        flash[:notice] = "Paid and Approved successfully!"
        redirect_to campaign_contents_path
      else
        reservation.Declined!
        flash[:alert] = "Cannot charge with this payment method!"
      end
    end
  rescue Stripe::CardError => e
    content.Declined!
    flash[:alert] = e.message
  end

  # Use callbacks to share common setup or constraints between actions.
  def set_campaign
    @campaign = Campaign.find(params[:campaign_id])
  end

  def set_content
    @content = @campaign.contents.find(params[:id])
  end

  # Only allow a trusted parameter "white list" through.
  def content_params
    params.require(:content).permit(:post_copy, :is_facebook, :is_instagram, :is_twitter, :is_youtube, :price, image: [])
  end
end

Content.rb

class Content < ApplicationRecord
  enum status: {Waiting: 0, Approved: 1, Declined: 2}

  after_create_commit :create_notification

  belongs_to :user
  belongs_to :campaign

  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

  private

  def create_notification
    type = self.campaign.Instant? ? "New Booking" : "New Request"
    influencer = User.find(self.user_id)

    Notification.create(content: "#{type} from #{influencer.fullname}", user_id: self.campaign.user_id)
  end
end

Terminal Response

Processing by ContentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"rM9i4hOlaYpVCmaUpHVRmh9N/QqI+nbnPvIJp3k9VlJ1U8rSb7FNTv9kqlR0P0LayZ6nUto2ekYXoTrCy45mWw==", "content"=>{"post_copy"=>"Testing for Stack Over Flow", "price"=>"10", "images"=>[], "is_instagram"=>"1"}, "commit"=>"Submit for Approval", "campaign_id"=>"1"}
  Campaign Load (0.2ms)  SELECT  "campaigns".* FROM "campaigns" WHERE "campaigns"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/contents_controller.rb:126
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/contents_controller.rb:25
  CACHE Campaign Load (0.0ms)  SELECT  "campaigns".* FROM "campaigns" WHERE "campaigns"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/contents_controller.rb:29
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/contents_controller.rb:32
Unpermitted parameter: :images
   (0.1ms)  begin transaction
  ↳ app/controllers/contents_controller.rb:39
  Content Create (1.1ms)  INSERT INTO "contents" ("user_id", "campaign_id", "post_copy", "is_instagram", "price", "transaction_fee", "total", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["user_id", 2], ["campaign_id", 1], ["post_copy", "Testing for Stack Over Flow"], ["is_instagram", 1], ["price", 10], ["transaction_fee", 1], ["total", 11], ["created_at", "2018-10-17 14:03:08.805281"], ["updated_at", "2018-10-17 14:03:08.805281"]]
  ↳ app/controllers/contents_controller.rb:39
   (6.1ms)  commit transaction
  ↳ app/controllers/contents_controller.rb:39
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
  ↳ app/models/content.rb:16
   (0.2ms)  begin transaction
  ↳ app/models/content.rb:18
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/models/content.rb:18
  Notification Create (0.7ms)  INSERT INTO "notifications" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["content", "New Request from Influencer"], ["user_id", 1], ["created_at", "2018-10-17 14:03:08.841715"], ["updated_at", "2018-10-17 14:03:08.841715"]]
  ↳ app/models/content.rb:18
   (3.8ms)  commit transaction
  ↳ app/models/content.rb:18
[ActiveJob] Enqueued NotificationJob (Job ID: 61665383-2b84-4215-95c2-47f6a5b98153) to Async(default) with arguments: #<GlobalID:0x00007fdf094d0928 @uri=#<URI::GID gid://Notification/17>>
Redirected to http://localhost:3000/campaigns/1
  Notification Load (0.4ms)  SELECT  "notifications".* FROM "notifications" WHERE "notifications"."id" = ? LIMIT ?  [["id", 17], ["LIMIT", 1]]
Completed 302 Found in 71ms (ActiveRecord: 14.2ms)
13
  • 1
    Can you please add controller code for saving data and form params from terminal ? Commented Oct 17, 2018 at 13:50
  • Added the controller Commented Oct 17, 2018 at 13:52
  • Sorry, I'm new at this so not sure about certain things. Commented Oct 17, 2018 at 13:54
  • First try to change file_field_tag to f.file_field because in tags, params have different name then the params with f obejct so this might be causing problem First try with f.file_field. Commented Oct 17, 2018 at 13:56
  • I haved changed it to <%= f.file_field "images[]", type: :file, multiple: true %> still the images are not uploading Commented Oct 17, 2018 at 13:59

1 Answer 1

1

Unpermitted parameter: :images

Your code needs a couple of important changes.

1) This

<%= file_field_tag "images[]", type: :file, multiple: true %>

should be

<%= f.file_field "image[]", type: :file, multiple: true %>

2) You need to modify content_params to allow image to accept an array of values. Change :image to image: [] in the content_params

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

10 Comments

Thanks but now I'm getting an error from the controller. "unknown attribute 'images' for Content."
@PeeyushVerma I've updated my answer. Change images to image in the answer.
Thanks for the swift response. However, now the error is Paperclip::AdapterRegistry::NoHandlerError (No handler found for []):
@PeeyushVerma What happens when you change this <%= f.file_field "image[]", type: :file, multiple: true %> to <%= f.file_field image, type: :file, multiple: true %>?
When changed <%= f.file_field "image[]", type: :file, multiple: true %> to <%= f.file_field image, type: :file, multiple: true %> I got an error ActiveModel::UnknownAttributeError (unknown attribute 'images' for Content.):
|

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.