TredOut
TredOut

Reputation: 57

Paperclip - Can't upload a picture

Model

class Pin < ActiveRecord::Base
    attr_accessible :description, :image
    has_attached_file :image, styles: { medium: "320x240>"}

    validates :description, presence: true
    validates :user_id, presence: true
    validates_attachment :image, presence: true,
                        content_type: { content_type: ["image/jpeg", "image/jpg", "image/gif", "image/png"] },
                        size: { in: 0..5.megabytes }


    belongs_to :user

end

I choose the image I want to upload, fill in the text, submit it and then I get the error message "This field [image] can't be blank" eventhough it really wasn't. Where could be the problem?

Upvotes: 0

Views: 596

Answers (2)

Graham S.
Graham S.

Reputation: 1530

It sounds like you might not have whitelisted your name of your file_field. I am not sure which version of Rails you are using, so I'll provide and answer for both 3 and 4.

In your view:

<%= form_for @pin do |f| %>
    <%= f.file_field :image %>
<% end %>

In your controller:

Rails 4

def create
    @pin = Pin.new(pin_params)

    if @pin.save
       # do your success calls here
    else
       # do your error calls here
    end
end

private
def pin_params
    # whitelist it here with "Strong Parameters" if you're using Rails 4
    params.require(:pin).permit(:image)
end

if using Rails 3

# ==== Pin.rb model ====
# whitelist it in your model with attr_accessible
class Pin < ActiveRecord::Base
    attr_accessible :image

    validates :description, presence: true
    validates :user_id, presence: true
    validates_attachment :image, presence: true,
                    content_type: { content_type: ["image/jpeg", "image/jpg", "image/gif", "image/png"] },
                    size: { in: 0..5.megabytes }

    belongs_to :user
end

#===== PinsController.rb =======
def create
    @pin = Pin.new(params[:image])

    if @pin.save
       # do your success calls here
    else
       # do your error calls here
    end
end

Upvotes: 2

soltex
soltex

Reputation: 3521

The problem is that you didn't permit that parameter to be access, to do that add :image parameter in your controller parameters require, so you can access it, something like this:

params.require(:pin).permit(YOUR PARAMETERS HERE, :image)

Upvotes: 4

Related Questions