rails paperclip mysql does not save files - ruby-on-rails

The attachment resume seems to works fine, but i do not have any insert into database (null, null, null , null) and i do not have file uploaded to any folder in my app...
class AddAttachmentCvToUsers < ActiveRecord::Migration
def change
change_table :users do |t|
t.attachment :cv
end
end
end
User model :
attr_accessor :cv
validates_attachment :cv
has_attached_file :cv, :path=>":rails_root/storage/#{Rails.env}#{ENV['RAILS_TEST_NUMBER']}/."
I have also installed carrierwave but still no effects..
Edit:
User Controller (I do not have another controller for attachments) :
class UsersController < ApplicationController
def new
#users = User.new
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
current_user = #user.id
redirect_to '/status'
else
redirect_to '/signup'
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :PESEL, :phone, :password,:cv)
end
end
View for new user with attachement:
<div class="login">
<div class="container">
<div class="form">
<h1>SIGN UP</h1>
<%= form_for #users,:html=> {:multipart=>true} do |f| %>
<%= f.text_field :first_name, :placeholder => "First name" %>
<%= f.text_field :last_name, :placeholder => "Last name" %>
<%= f.email_field :email, :placeholder => "Email" %>
<%= f.text_field :PESEL, :placeholder => "PESEL number" %>
<%= f.phone_field :phone, :placeholder => "Phone Number" %>
<%= f.password_field :password, :placeholder => "Password" %>
<p>CV</p>
<%= f.file_field :cv, name: "CV", class: 'form-control' %>
<%= f.submit "Sign up", class: "btn-submit" %>
<% end %>
</div>
</div>
</div>
Some logs from console:
Started POST "/users" for 127.0.0.1 at 2016-05-18 03:55:17 +0200
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Fw6easThY51CDppDDVfqO0ProQITaltqP3DaIL3An67ey4vGXh2yEerhhhxoo3bTp/mKbkIaAmktzBviBIjg8g==", "user"=>{"first_name"=>"Test", "last_name"=>"Test", "email"=>"test#t.pl", "PESEL"=>"91020300441", "phone"=>"609123123", "password"=>"[FILTERED]"}, "CV"=>#<ActionDispatch::Http::UploadedFile:0x007f25790c1b60 #tempfile=#<Tempfile:/tmp/RackMultipart20160518-26849-rqaabr.pdf>, #original_filename="pdf-test.pdf", #content_type="application/pdf", #headers="Content-Disposition: form-data; name=\"CV\"; filename=\"pdf-test.pdf\"\r\nContent-Type: application/pdf\r\n">, "commit"=>"Sign up"}
(0.1ms) BEGIN
User Exists (1.4ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'test#t.pl' LIMIT 1
User Exists (0.1ms) SELECT 1 AS one FROM `users` WHERE `users`.`PESEL` = BINARY '91020300441' LIMIT 1
SQL (0.1ms) INSERT INTO `users` (`first_name`, `last_name`, `email`, `PESEL`, `phone`, `password_digest`, `created_at`, `updated_at`) VALUES ('Test', 'Test', 'test#t.pl', '91020300441', '609123123', '$2a$10$HmHAiJkHv1Tada/OpzKXKOISiwumoFKTy48tFpNBYuATq/A5GaC9G', '2016-05-18 01:55:17', '2016-05-18 01:55:17')
SQL (1.0ms) INSERT INTO `job_apps` (`user_id`, `created_at`, `updated_at`) VALUES (35, '2016-05-18 01:55:17', '2016-05-18 01:55:17')
(3.0ms) COMMIT
Redirected to http://localhost:3000/status
Completed 302 Found in 135ms (ActiveRecord: 8.2ms)
Started GET "/status" for 127.0.0.1 at 2016-05-18 03:55:17 +0200
Processing by JobAppsController#index as HTML

You have overridden the name attribute of the file_field, which has broken Rails naming conventions. If you remove the name attribute, Rails will be able to pass the file details uploaded in the :cv field to the database.
Change the file_field to this:
<%= f.file_field :cv, class: 'form-control' %>
If you have Javascript attached to the form, and need to refer to the file_field element, you can use this, instead:
<%= f.file_field :cv, id: "cv", class: "form-control" %>

Related

Broken User Registration Form in Ruby on Rails

I'm having an issue with my user registration form in Ruby on Rails.
I had it working before simply with just a username, email, and password. However when I tried to add fields for first name, last name, and ZIP code, it stopped inserting any data into the database, and just redirects back to the registration form.
I did it the correct way with generating migrations and migrating the db- the form still wasn't working.
I then dropped the database entirely and recreated it with all of the fields included, and it still won't work. The database was generated correctly with the correct fields, and I'm not sure where the disconnect is.
I'm using ruby 2.3.1.
Users controller:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
redirect_to '/home'
else
redirect_to '/register'
end
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :location, :fname, :lname)
end
end
User model:
class User < ApplicationRecord
has_secure_password
end
Form at users/new:
<div class="container">
</div>
<div id="contact" class="container-fluid bg-grey">
<h2 class="text-center">Create An Account</h2>
<form>
<%= form_for(#user) do |f| %>
<%= f.text_field :username, :placeholder => "Username" %>
<%= f.email_field :email, :placeholder => "Email" %>
<%= f.password_field :password, :placeholder => "Password" %><br/><br/>
<%= f.text_field :fname, :placeholder => "First Name" %>
<%= f.text_field :lname, :placeholder => "Last Name" %>
<%= f.number_field :location, :placeholder => "ZIP Code (US Only)" %><br/><br/>
<%= f.submit "Create an Account", class: "btn-submit" %>
<% end %>
</div>
</ul>
</nav>
</body>
</html>
Create users migration:
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password_digest
t.numeric :location
t.string :fname
t.string :lname
t.timestamps
end
end
end
From log:
Started GET "/register?utf8=%E2%9C%93&authenticity_token=b6M1gpQx8BTLhBqjjh6R%2BlSGghcSh18Mg7eGskLGNyq11RBvGCX%2BOJjVhSLwwRmZunn1sYvV4MGHB7vrJw6Rhg%3D%3D&user%5Busername%5D=jsmith1&user%5Bemail%5D=jsmith%40email.com&user%5Bpassword%5D=[FILTERED]&user%5Bfname%5D=John&user%5Blname%5D=Smith&user%5Blocation%5D=60606&commit=Create+an+Account" for ::1 at 2016-11-07 15:14:50 -0600
Processing by UsersController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"b6M1gpQx8BTLhBqjjh6R+lSGghcSh18Mg7eGskLGNyq11RBvGCX+OJjVhSLwwRmZunn1sYvV4MGHB7vrJw6Rhg==", "user"=>{"username"=>"jsmith1", "email"=>"jsmith#email.com", "password"=>"[FILTERED]", "fname"=>"John", "lname"=>"Smith", "location"=>"60606"}, "commit"=>"Create an Account"}
Rendering users/new.html.erb within layouts/application
Rendered users/new.html.erb within layouts/application (2.0ms)
Completed 200 OK in 195ms (Views: 148.1ms | ActiveRecord: 21.5ms)
)
Completed 200 OK in 760ms (Views: 714.8ms | ActiveRecord: 3.5ms)
Thank you so much for any help.
I figured it out. The extra form tag was messing with the form submission. Once I removed <form> from above the Ruby form code, it worked. Thank you to the people who responded.

nested attributes and form not saving Rails 4

I am trying to nest a user to an account and allow the user to be created when the account is created. I am having an issue when creating both the account and user from the same form, and my server output is not very helpful in trying to isolate the problem.
here is the output when I try to save the Account and User.
Started POST "/accounts" for ::1 at 2016-10-10 20:55:23 -0600
Processing by AccountsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"UK7h4edNzRomi7JGomoZD1ayYmlNxI/h2ZH+NEaJxWQzcFsYAJujr5EDDS2HeprAX41IuS5/crRxmXYz80YpYw==", "account"=>{"subdomain"=>"mydomain", "owner_attributes"=>{"email"=>"swilson#ta#####td.com", "f_name"=>"S####", "l_name"=>"W####", "date_of_birth"=>"19##-##-##", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}, "commit"=>"Create Account"}
(0.3ms) BEGIN
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "swilson#ta#####td.com"], ["LIMIT", 1]]
Account Exists (0.3ms) SELECT 1 AS one FROM "accounts" WHERE "accounts"."subdomain" IS NULL LIMIT $1 [["LIMIT", 1]]
(0.2ms) ROLLBACK
Rendering accounts/new.html.erb within layouts/application
Rendered accounts/_form.html.erb (3.8ms)
Rendered accounts/new.html.erb within layouts/application (5.1ms)
Rendered shared/_signed_out_nav.html.erb (1.3ms)
Completed 200 OK in 183ms (Views: 44.2ms | ActiveRecord: 1.1ms)
I believe the issue may have something to do with the account generation and the subdomain. but I Can not pin it down for the life of me!
also I commented out my personal info with the ####...
here is my account controller
class AccountsController < ApplicationController
def new
#account = Account.new
#account.build_owner
end
def create
#account = Account.new(account_params)
respond_to do |format|
if #account.save
format.html {redirect_to root_path, notice: 'Account successfully created.'}
else
format.html {render :new, alert: 'There was a problem, please try again.'}
end
end
end
private
def account_params
params.require(:account).permit(:subdomain, owner_attributes: [:email, :password, :password_confirmation, :f_name, :l_name, :date_of_birth])
end
def set_account
#account = Account.find(params[:id])
end
end
here is my account form:
<%= bootstrap_form_for(#account) do |f| %>
<div class="row">
<div class="col-xs-12">
<%= f.text_field :subdomain, hide_label: true, placeholder: 'Company Name', append: ".patrolvault.net" %>
</div>
</div>
<%= f.fields_for :owner do |o| %>
<div class="row">
<div class="col-xs-12">
<%= o.email_field :email, label: 'Email Address' %>
</div>
<div class="col-xs-12">
<%= o.text_field :f_name, label: 'First Name' %>
</div>
<div class="col-xs-12">
<%= o.text_field :l_name, label: 'Last Name' %>
</div>
<div class="col-xs-12">
<%= o.date_field :date_of_birth, label: 'Date Of Birth' %>
</div>
<div class="col-xs-6">
<%= o.password_field :password, label: 'Password' %>
</div>
<div class="col-xs-6">
<%= o.password_field :password_confirmation, label: 'Confirm Password' %>
</div>
</div>
<% end %>
<%= f.submit :class => 'btn btn-primary' %>
<% end %>
and here is my account model:
class Account < ApplicationRecord
# Before Actions
before_validation :downcase_subdomain
# Relationships
belongs_to :owner, class_name: 'User', optional: true
accepts_nested_attributes_for :owner
# Validations
validates :owner, presence: true
RESTRICTED_SUBDOMAINS = %w(www, patrolvault, test)
validates :subdomain, presence: true,
uniqueness: { case_sensitive: false },
format: { with: /\A[\w\-]+\Z/i, message: 'Contains invalid characters.' },
exclusion: { in: RESTRICTED_SUBDOMAINS, message: 'Restricted domain name'}
# Custom Methods
private
def downcase_subdomain
self.subdomain = subdomain.try(:subdomain)
end
end
Please let me know if you require further info or if I have missed something! Thanks!
so the problem was in my before_validation :downcase_subdomain. once I removed that and the matching method everything began to work fine. I will rework this.
Thanks.

Update two records from different tables with nested form

My form is updating the tester record (which is an end user). I am also trying to update many applied_program records which belong to the tester.
I am sending the parameters to the controller but cannot get it to update the the applied_program records. It is trying to use all the parameters instead of just the applied program params to update it.
Form:
<%= form_for #tester, url: { controller: :admins, action: :update_tester } do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name, class: "input-lg" %>
...
<%= f.fields_for :applied_programs do |fml| %>
<%= fml.label :approved, "Approved: " %><%= fml.check_box :approved %>
<%= fml.hidden_field :id %>
<% end %>
<%= f.submit "Save Changes", class: "btn btn-lg btn-primary" %>
<% end %>
Tester Model:
has_many :applied_programs, :dependent => :destroy
accepts_nested_attributes_for :applied_programs
AppliedProgram Model:
belongs_to :tester
Controller:
def update_tester
#applied_programs = AppliedProgram.where(tester_id: #tester.id)
#tester.update_attributes(tester_params)
#applied_programs.each do |p|
p.update_attributes(tester_params)
end
end
def tester_params
params.require(:tester).permit(:name, :email, :phone_number, :address1,
:city, :zip_code, :country, :password, :password_confirmation,
:active, :approved, applied_programs_attributes: [ :approved, :id ])
end
The log:
Processing by AdminsController#update_tester as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x", "tester"=>{"name"=>"Dave", "email"=>"nope#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "applied_programs_attributes"=>{"0"=>{"approved"=>"0", "id"=>"9"}, "1"=>{"approved"=>"1", "id"=>"745"}}}, "commit"=>"Save Changes", "id"=>"16"}
Tester Load (0.1ms) SELECT `testers`.* FROM `testers` WHERE `testers`.`id` = 16 LIMIT 1
Tester Load (1.1ms) SELECT `testers`.* FROM `testers` WHERE `testers`.`remember_token` = 'x' LIMIT 1
(6.8ms) BEGIN
AppliedProgram Load (2.6ms) SELECT `applied_programs`.* FROM `applied_programs` WHERE `applied_programs`.`tester_id` = 16 AND `applied_programs`.`id` IN (9, 745)
Tester Exists (0.8ms) SELECT 1 AS one FROM `testers` WHERE (`testers`.`email` = 'nope#gmail.com' AND `testers`.`id` != 16) LIMIT 1
(0.1ms) COMMIT
AppliedProgram Load (0.1ms) SELECT `applied_programs`.* FROM `applied_programs` WHERE `applied_programs`.`tester_id` = 16
(0.1ms) BEGIN
(12.4ms) ROLLBACK
Completed 500 Internal Server Error in 95ms
ActiveRecord::UnknownAttributeError (unknown attribute: name)
You problem is the loop over the applied_programs you need to do something like:
def update_tester
#applied_programs = AppliedProgram.where(tester_id: #tester.id)
#tester.update_attributes(tester_params)
end
def tester_params
params.require(:tester).permit(:name, :email, :phone_number, :address1,
:city, :zip_code, :country, :password, :password_confirmation,
:active, :approved, applied_programs_attributes: [ :approved, :id ])
end

Rails not updating attribute

Pretty standard update in my opinion, but upon submitting the put request, the attribute is not updated. Here is my relevant model:
class Vendor < ActiveRecord::Base
geocoded_by :address
after_validation :geocode,
:if => lambda{ |obj| obj.address_changed? }
end
My controller methods:
def edit
#vendor = Vendor.find(params[:id])
end
def update
#vendor = Vendor.find(params[:id])
if #vendor.update_attributes(vendor_params)
redirect_to vendors_mgmt_path
else
render 'edit'
end
end
def vendor_params
params.permit(:id, :name, :address, :image, :latitude, :longituded )
end
I see this in the server log after trying to update:
Started PUT "/vendors/1" for 127.0.0.1 at 2013-10-20 20:44:54 -0700
Processing by VendorsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"fTbZVEfckQz4xQzY5xSMQCArrGZqymNsVeyic/PXKcE=", "vendor"=>{"name"=>"Store", "address"=>"1221 E. Main St."}, "commit"=>"Save changes", "id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Vendor Load (0.2ms) SELECT "vendors".* FROM "vendors" WHERE "vendors"."id" = ? LIMIT 1 [["id", "1"]]
Unpermitted parameters: utf8, _method, authenticity_token, vendor, commit
(0.1ms) begin transaction
(0.1ms) commit transaction
Redirected to http://localhost:3000/vendors/mgmt
Completed 302 Found in 10ms (ActiveRecord: 0.6ms)
This confuses me, because the Vendor form looks like so, and has no authenticity token etc.
<h1>Update <%= "#{#vendor.name}" %></h1>
<%= form_for(#vendor) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :address %>
<%= f.text_field :address %>
<%= f.label :Logo %>
<%= f.file_field :image %>
<%= f.submit "Save changes", class: "btn btn-success" %>
<% end %>
Anyone see any glaring errors? Any help is much appreciated. Thanks in advance!
Rails by default includes certain hidden fields in all forms, such as the authenticity_token, which is present to stop CSRF. (More info here) I would recommend changing the line:
params.permit(:id, :name, :address, :image, :latitude, :longituded )
to:
params.require(:vendor).permit(:id, :name, :address, :image, :latitude, :longituded)
Changing this line in your controller should permit the other parameters that are submitted by the form, not just the ones in the vendor param.
Also, you misspelled "longitude", I'm not sure if that's causing any additional trouble or if it's just a typo in your question instead.

rails form skips validation and doesn't save

My rails form skips validation and doesn't save. Any ideas on why this is happening?
What ends up happening is that the form submits and it goes to the create action, but it skips the validation completely set up in contact.rb and this line in the contact controller's #contact.save doesn't save and it goes to the else.
This is what gets printed in the terminal server window after the contact form gets submitted with dummy data:
logged in #<Contact:0xb60b3978>
Started POST "/contacts" for 127.0.0.1 at 2013-08-11 17:04:46 -0400
Processing by ContactsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zbEGKGXz1t2Os6VjVOMzcfeHru9sBfoBaF6tgr16qPo=", "contact"=>{"name"=>"", "email"=>"", "subject"=>"", "body"=>""}, "category"=>"bug", "commit"=>"Contact Us"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
(0.1ms) begin transaction
(0.1ms) rollback transaction
Redirected to http://localhost:3000/contact
Completed 302 Found in 9ms (ActiveRecord: 0.3ms)
Started GET "/contact" for 127.0.0.1 at 2013-08-11 17:04:46 -0400
Processing by ContactsController#new as HTML
Rendered common/_form_errors.html.erb (0.0ms)
Rendered contacts/_contact_form.html.erb (2.3ms)
Rendered contacts/new.html.erb within layouts/application (2.9ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
Rendered common/_search_form.html.erb (0.5ms)
Rendered layouts/_navbar.html.erb (4.2ms)
Rendered layouts/_flashmessages.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 72ms (Views: 71.2ms | ActiveRecord: 0.2ms)
Contact.rb:
class Contact < ActiveRecord::Base
belongs_to :user
attr_accessible :body, :category, :email, :name, :subject
validates :body, presence: true, length: { in: 10..255 }
validates :category, presence: true
validates :name, presence: true
validates :email, presence: true
validates :subject, presence: true
end
_contact_form.html.erb:
<%= form_for(#contact) do |f| %>
<%= render 'common/form_errors', object: #contact %>
<div class="span4">
<div class="well">
<%= f.label :name, "What's your name?" %>
<%= f.text_field :name, :class => "field span4" %>
</div>
<div class="well">
<%= f.label :email, "Your Email so we can hit you back." %>
<%= f.text_field :email, :class => "field span4" %>
</div>
<div class="well">
<%= f.label :category, "Pick one:" %>
<%= select_tag(:category,
options_for_select(
[['I found a bug.', 'bug'], ['I have a suggestion.', 'suggestion'], ['other', 'other']]
)) %>
</div>
<div class="well">
<%= f.submit "Contact Us", :class=> "marginTopBottom" %>
</div>
</div>
<div class="span4">
<div class="well">
<%= f.label :subject, "Subject:" %>
<%= f.text_field :subject, :class => "field span4" %>
</div>
<div class="well">
<%= f.label :body, "What's Up?" %>
<%= f.text_area(:body, :rows => 7, :class => "field span4") %>
</div>
</div>
<% end %>
contacts/new.html.erb:
<%= provide(:navActive, 'Contact Us') %>
<h1>Contact Us</h1>
<div class="row">
<%= render 'contact_form' %>
</div>
contacts_controller.rb:
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
if logged_in?
#contact = current_user.contacts.build(params[:contact])
puts "logged in #{#contact}" # prints out when logged in
else
#contact = Contact.new(params[:contact])
#contact.user_id = 999999
puts "not logged in #{#contact}" # prints out when not logged in
end
if #contact.save
flash[:success] = "Your message was sent and we'll get back to you as soon as possible!"
# send an email to offering poster about the new request
UserMailer.contact(#contact, sent_at = Time.now).deliver
redirect_to contact_path
else
flash[:success] = "Your message was not sent. Something went wrong. Please contact pavankat#gmail.com."
redirect_to contact_path
end
end
end
routes.rb
resources :contacts, only: [:new, :create]
schema.rb:
create_table "contacts", :force => true do |t|
t.string "name"
t.string "email"
t.string "category"
t.string "subject"
t.string "body"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
end
add_index "contacts", ["user_id"], :name => "index_contacts_on_user_id"
I don't think it's skipping the validation, I think there's no way for your page to show the error.
You need to add <%= flash[:success] %> somewhere on the page.
You can also output errors for the contact object, which might help!
(You may refute this by posting the content of common/form_errors -
It should be:
<%= f.select(:category,
options_for_select(
[['I found a bug.', 'bug'], ['I have a suggestion.', 'suggestion'], ['other', 'other']]
)) %>

Resources