Aniee
Aniee

Reputation: 81

match regex in controller condition in rails4

Hi i given this in my controller action :

def create
    @department = Department.create(department_params)
    if @department.attachment.attach_content_type == 'image\/.*'
      render :action => :new
    else
      redirect_to departments_path, notice: I18n.t('department_created')
    end
  end

and I am getting this in my params

Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y2GmRyk6SEh12vJQMEWpdphojFeCXWxhECLaJ1bBww6sZ7P9CmjLEmxK/vGPx2tZ+15zy0W4+tYf26zpHSL9Yw==", "department"=>{"name"=>"Quality Assurancebnnnnnnnnnnnn", "attachment_attributes"=>{"attach"=>#<ActionDispatch::Http::UploadedFile:0xb41fac20 @tempfile=#<Tempfile:/tmp/RackMultipart20150608-4331-a3x9h7.jpeg>, @original_filename="index.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"department[attachment_attributes][attach]\"; filename=\"index.jpeg\"\r\nContent-Type: image/jpeg\r\n">}}, "button"=>""}

its not going inside my if condition it goes in my else part but content_type is image/jpeg and I want if my content_type starts from image then it will not save. I had tried this also

p "*********************************8"
    p (@department.attachment.attach_content_type).to_s
    @content_type = (@department.attachment.attach_content_type).to_s
    p 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr'
    p @content_type == "image\/.*" 

but it gives me this output in console :

"*********************************8"
"image/jpeg"
"rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
false

Please guide how to solve this.

Upvotes: 0

Views: 262

Answers (1)

arco444
arco444

Reputation: 22831

You have defined your regex as a string: 'image\/.*'

Try instead:

if @department.attachment.attach_content_type.to_s =~ /image\/.*/

Upvotes: 2

Related Questions