Невозможно загрузить изображения с помощью скрепки на рельсах 5 - PullRequest
0 голосов
/ 17 октября 2018

ошибка

Ошибка при загрузке изображения

Я не могу загрузить изображение в моей вложенной форме скаффолда.

Все остальные поля попадают в базу данных, кроме изображения.Пожалуйста, помогите!

Я на рельсах 5.2 и использую скрепку для загрузки изображений, и изображения должны быть загружены на AWS.

Я не получаю никаких ошибок, просто изображения не поступают в базу данных.

Спасибо!

Форма Частичная

    <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 !@campaign.facebook.blank? %>
  <div class="col-md-3">
    <%= f.check_box :is_facebook %> Facebook
  </div>
  <% end %>

  <% if !@campaign.twitter.blank? %>
  <div class="col-md-3">
    <%= f.check_box :is_twitter %> Twitter
  </div>
  <% end %>

  <% if !@campaign.instagram.blank? %>
  <div class="col-md-3">
    <%= f.check_box :is_instagram %> Instagram
  </div>
  <% end %>

  <% if !@campaign.youtube.blank? %>
  <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>

Контроллер

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

Ответ терминала

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)

1 Ответ

0 голосов
/ 17 октября 2018

Недопустимый параметр:: images

Ваш код нуждается в нескольких важных изменениях.

1) Это

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

должно быть

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

2) Вам нужно изменить content_params, чтобы image мог принимать массив значений.Измените :image на image: [] в content_params

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...