Rails - update_attributes coming up against validations - ruby-on-rails

So I've got a user model, with login, email address, password, password confirmation, name, avatar (picture), etc. There are validations on the first 5, basically stating that all 5 need to exist in order to create a new model.
However, this causes problems for me where updates are concerned.
I've got an edit page, where the user can only edit their name and avatar. I'm not currently intending to let them change their login, and I wish to do an email and password change from a different page.
So the edit form looks like this:
<% form_for #user, :html => { :multipart => true } do |u| %>
<p>
<label>Name:</label>
<%= u.text_field :name %>
</p>
<p>
<label>Avatar:</label>
<%= display_user_avatar %>
<%= u.file_field :avatar%>
</p>
<p>
<%= submit_tag %>
</p>
<% end %>
If I attempt to do a #user.update_attributes(params[:user]), then because the only 2 params are name and avatar, the update fails, since stuff like password, password confirmation, email, etc are required to validate the entry, and they simply don't exist in that form.
I can get around this by doing #user.update_attribute(:name, params[:user][:name]), but then I worry about whether avoiding validations is a Good Thing™ or not. Especially with regards to something like password updates, where I do need to validate the new password.
Is there another way?
And if I were to do this simply using update_attribute for :name and :avatar, how would I go about doing it?
Would this work?
params[:user].each do |attribute|
#user.update_attribute(attribute, params[:user][attribute])
end
Is this an acceptable way to do this...?
--edit as follow up --
Okie, I tried as you suggested and did
def update
#user = User.find_by_login(params[:id])
if #user.update_attributes!(params[:user])
redirect_to edit_user_path(#user)
else
flash[:notice] = #user.errors
redirect_to edit_user_path(#user)
end
end
So it's doing the ! version, and the exception caught & displayed in the browser is:
Validation failed: Password is too short (minimum is 5 characters)
The info in the server log is:
Processing UsersController#update (for 127.0.0.1 at 2010-07-18 11:56:59) [PUT]
Parameters: {"user"=>{"name"=>"testeeeeee"}, "commit"=>"Save changes", "action"=>"update", "_method"=>"put", "authenticity_token"=>"BMEGRW/pmIJVs1zlVH2TtZX2TQW8soeCXmMx4kquzMA=", "id"=>"tester", "controller"=>"users"}
Urm. Looking at this, I just realised that it is submitting "id"=>"tester". Now, I have my routes set up so that it is showing the users login name, instead of the user_id... Could that be why? It is attempting to find a update a user with user_id == tester, but since it doesn't exist, it attempts to create one instead?
Is it actually something I'm doing wrong due to the route?
Hmmm... rake routes tells me that the route is:
edit_user GET /users/:id/edit(.:format) {:action=>"edit", :controller=>"users"}
PUT /users/:id(.:format) {:action=>"update", :controller=>"users"}
And I set up the route like that in the user.rb file:
def to_param
"#{login}"
end
but it's definitely been displaying login instead of id all this time. But I'm also doing right at the beginning of the update action, a #user = User.find_by_login(params[:id]), and then updating that #user.
I'm very confused. >.<
Second update:
My User.rb validation stuff are as follows:
validates_length_of :login, :within => 3..20
validates_length_of :password, :within => 5..20
validates_presence_of :login, :email, :password, :password_confirmation, :salt, :name, :on => :create
validates_uniqueness_of :login, :case_sensitive => false
validates_confirmation_of :password
validates_format_of :email, :with => /^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "format is invalid."
attr_accessor :password, :password_confirmation
And the hashed_password section is here:
def password=(pass)
#password = pass
self.salt = User.random_string(10) if !self.salt?
self.hashed_password = User.encrypt(#password, self.salt)
end
u.attributes gives me
>> u.attributes
=> {"salt"=>"NHpH5glxsU", "name"=>"test er", "avatar_updated_at"=>nil, "updated_at"=>Sat Jul 17 07:04:24 UTC 2010, "avatar_file_size"=>nil, "avatar_file_name"=>nil, "hashed_password"=>"84f8675c1ed43ef7f8645a375ea9f867c9a25c83", "id"=>1, "avatar_content_type"=>nil, "login"=>"tester", "email"=>"tester#tester.com", "created_at"=>Fri May 07 10:09:37 UTC 2010}
Urmmm... Ok, so it's what you said, about the virtual attribute password being actually nonexistent...
So how do I get around that?
Bugger, here I thought I was being smart fiddling with my own authentication code...
How easy is it to change to one of those authentication plugins? Will I need to create a new User model? Or should the plugin be able to work with my current one?
Thanks for all the help so far, btw! :D

I've checked this and a partial update of just 2 attributes via update_attributes works fine. All the other attributes are left with their previous values, meaning that the validation shouldn't fail. A couple of things to try:
In your controller action are you loading the user via User.find? i.e. are you starting from a valid model.
Are you sure the update is failing due to validation errors? Try replacing the update_attributes with update_attributes!. The latter will throw an exception if the update fails due to validation. Or check #user.errors after the attempted update to confirm which validation has failed.
Update
If User.find_by_login doesn't find a matching record it will return nil and won't create a new record for you. Is it possible that the tester user in the database has a password that is too short? Maybe that user was created before you put the validations in your code? Are you using any kind of plugin or callback to encrypt user passwords before saving the records? Is password actually a virtual attribute that isn't saved and the actual password is in a field like encrypted_password?
Try this from script/console (use the same environment as you are testing the app with - development or production)
> user = User.find_by_login 'tester'
> user.valid?
> user.attributes
The user.valid? will return true of false and will tell you whether the user is valid to start with, before you even try an update.
Update 2 (fixing the validation)
In terms of fixing your own code, you could add a method like the following to your User model:
def password_validation_required?
hashed_password.blank? || !#password.blank?
end
and then update all your password related validation rules so that they only apply if this method returns true e.g.
validates_length_of :password, :within => 5..20,
:if => :password_validation_required?
What this is saying is only do the password validation rule if we don't yet have a hashed_password (on a new user for example) or if a new plain text password has been specified via password=. If the user already has a password and it is being left unchanged then skip the password validation.
You are right to be considering using a plugin though. Writing your own authentication code can be an interesting excercise and can be required if you have some unusual requirements. The down side is that there can be security issues that you haven't thought of. Retrofitting something like restful_authentication to your app shouldn't be too bad. You might just need to rename one or two fields on your User model.

Related

rails 5 "password" disappears from params

(This is not about filtered parameters in logfiles.)
I have in my view
<%= password_field_tag :password, '', autofocus: true, class: 'form-control' %>
and then in my controller
#password = params[:password]
In Rails 4 I can use #password to authenticate, all works fine.
In Rails 5, params does NOT contain :password anymore. If I change :password to :password1 in view and controller, all is fine, so somehow :password is filtered out.
I checked for config.filter_parameters (which controles log file filtering) - removed 'password' from it, but it did not influence this behavior.
What am I missing?
May not be the case for the OP but this manifested for me porting an App to Rails 5
This can happen when the parameters are passed into the action at the root level, instead of being scoped: for example for a user registration:
params: { email: "best#buddy.com", password: "passw0rd" }
The Rails (5 at least) parameter wrapper creates 'magic' nested params under the 'user' key (from the controller name) so by the time it reaches your controller action this is actually what is present:
params: { email: "best#buddy.com", password: "passw0rd", user: { email: "best#buddy.com"} }
Notice that the email value was copied underneath the user key! This feels like WTF, but I'm sure there are good reasons to do this. It happens in /actionpack-5.2.2.1/lib/action_controller/metal/params_wrapper.rb#250 during process_action
But given that this is done it may be a bug that the password is not also copied. But this is filtered out by request.filteres_parameters.slice(*wrapped_keys)
So the moral of the story is, nest your form params under the model name.
The reason I assume the OP saw the bug is the use of the password_field_tag which probably creates a :password param outside of the :user namespace key
params: { :password => "passw0rd" }
Instead of the
params: { :user => { :password => "passw0rd" } }
The controller is probably looking for :user..:password (If strong params are being used)
The reason this isn't surfacing as an obvious problem for the rest of the form fields is because the parameter wrapping is copying all the others into params[:user]
Mental Note the filtering of the password is possibly based on the Log filtering configuration?

Customize validation error message depending on the context

I need to have different error messages for the same model depending on the form's context and location.
For the User model which validates presence of first_name:
In the back-office page it is OK to have the validation message "First name can't be blank"
In the registration page the message should be "Please type your first name"
I am looking for a clean and best-practice oriented solution, because I would like not to hack with view helper and such.
Any hint appreciated, thanks
You can use validate method in User model . Something like this
validate do |user|
if user.first_name.blank? && user.id.blank?
# id blank means the user is in registration page as he is new user.
user.errors.add(:base, "Please type your first name")
elsif user.first_name.blank?
user.errors.add(:base, "First name can't be blank")
end
end
May be using hidden_field and attr_accessor, I hope you can achieve what you want,
Form 1:
<%= f.hidden_field :check_form, :value => true %>
Form 2:
<%= f.hidden_field :check_form, :value => false %>
You need to pass check_form value also to the model.
Model:
attr_accessor :check_form
validates_presence_of :first_name, :if => :check_form_is_true?, :message => "First Name can't be blank"
validates_presence_of :first_name, :unless => :check_form_is_true? //here you need to use i18n oriented translation to show the custom error message
private
def check_form_is_true?
check_form == true
end
config/locales/en.yml
en:
activerecord:
attributes:
user:
first_name: ""
errors:
models:
user:
attributes:
first_name:
blank: "Please type your first name"
Hope it helps :)

Rails 4 - Checkbox and Boolean Field

I have looked at loads of different articles on the web (some on here) about this issue but there are so many different suggestions, lots of which are outdated, that it has led me to ask here today...
I have a field in my Users table called admin? which is a :boolean data type. I also have a checkbox in the form in my view called admin? - I would like to be able to create TRUE and FALSE accordingly in the table record when the form is submitted.
Part of my view code is:
Admin User? <%= f.check_box :admin? %>
Also I have permitted this in my post_params - is this a necessary step?
params.require(:staff).permit(:name, :email, :password, :password_confirmation, :admin?)
When I submit the form at the moment, the admin? field is unaffected. Any advice would be much appreciated.
No need to name it ":admin?"
Just use this in your form:
Admin User? <%= f.check_box :admin %>
And the permitted params like this:
params.require(:staff).permit(:name, :email, :password, :password_confirmation, :admin)
That should work.
For anyone that has a form that isn't part of an object.
I found using checkbox syntax like:
= check_box 'do_this', '', {}, 'true', 'false'
Then in the controller side:
ActiveRecord::ConnectionAdapters::Column.value_to_boolean(params[:do_this])
Will give you the correct boolean value of do_this.
Examples:
[1] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("true")
=> true
[2] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("false")
=> false
[3] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("1")
=> true
[4] pry(main)> ActiveRecord::ConnectionAdapters::Column.value_to_boolean("0")
=> false
Edit:
The above is deprecated, use:
ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
It gives the same results as the examples above.
Rails 5
The above options don't work in Rails 5. Instead, use the following:
ActiveRecord::Type::Boolean.new.cast(value)
It's possible you have not allowed your controller to accept the admin field through params. In other words, an issue of strong parameters. Ensure that :admin is permitted in your model_params.

Validate field is unique compared to another field in same form

Say I have two fields in a new or edit form:
<%= f.text_field :email %>
<%= f.text_field :parent_email %>
How, in my model, can I validate that parent_email is different from email? The exclusion option seems like it might work, but I can't figure out how to access the email field's value within the model. Do I need to implement this in the controller instead?
validates :parent_email, exclusion: self.email # doesn't work, nor does :email
The following should work (but I guess there are cooler solutions out there):
class User
validate :email_differs_from_parent_email
private
def email_differs_from_parent_email
if email == parent_email
errors.add(:parent_email, "parent_email must differ from email")
end
end
end

Rails Model: How to make an attribute protected once it's created?

I was just wondering: How can i make an attribute "write once" ?
To be more precise, I'm using Devise and I want the user to be able to register with this email but then, once it's done, I want this email locked.
I read that forms can easily be bypass, so I want to make sure my model does that.
Also, i'm using in one of my form that: <%= f.email_field :email, :id => "email", :disabled => "disabled" %>
Is there any risks that an user can modify his email after being registered?
Thanks for your answers!
attr_readonly allows setting a value at creation time, then prevents modifying it on updates.
class MyModel < ActiveRecord::Base
attr_readonly :email
end

Resources