I'm trying to update a user object through a form. However, I don't want to allow usernames to be changed. I don't have the field present on the form. When I submit the form, it gives me an error that I cannot leave the username confirmation blank. Here's my controller:
def update
#partner = CommunityPartner.find(params[:id])
if #partner.update_attributes(allowed_update_params)
else
render('edit')
end
end
def allowed_create_params
params.require(:community_partner).permit(:name, :username, :display_email,
:username_confirmation,
:contact_method, :password,
:password_confirmation,
:phone_number, :address,
:description, :tags_string)
end
def allowed_update_params
params.permit!(:name) if params[:name]
params.permit!(:display_email) if params[:display_email]
params.permit!(:contact_method) if params[:contact_method]
params.permit!(:phone_number) if params[:phone_number]
params.permit!(:address) if params[:address]
params.permit!(:description) if params[:description]
params.permit!(:tags_string) if params[:tags_string]
end
How can I update only the params I'm allowing in the update action without touching the others?
EDIT: validation methods
validates(:name, presence: { on: :create })
validates(:username, presence: { on: :create }, confirmation: { on: :create }, uniqueness: true)
validates(:contact_method, presence: { on: :create })
validates(:username_confirmation, presence: { on: :create })
validates(:display_email, format: { with: VALID_EMAIL })
validates(:address, presence: { on: :create })
validates(:phone_number, presence: { on: :create })
validates(:description, presence: { on: :create })
Assuming that you have a validation on username_confirmation in the CommunityPartner model.
Use on: :create option on that validation. So, that validation would only be checked at the time of CommunityPartner record creation and not while updating(where you don't pass username_confirmation).
For example:
class CommunityPartner < ActiveRecord::Base
validates :username_confirmation, presence: true, on: :create
end
You can skip validation using update_all helper instead of update_attributes.
Related
I don't understand why I can't use self here?
class PayoutRequest < ApplicationRecord
validates :phone, confirmation: true, on: :create
validates :phone_confirmation, presence: true, on: :create
belongs_to :user, foreign_key: "user_id"
validates :amount, numericality: { only_integer: true, greater_than_or_equal_to: 300, smaller_than_or_equal: self.user.balance }
scope :paid, -> { where(:paid => true) }
scope :unpaid, -> { where(:paid => false) }
end
How can I write this?
Use a custom method, for example:
validate :amount_not_greater_than_balance
def amount_not_greater_than_balance
return if amount <= user.balance
errors.add(:amount, "can't be greater than balance")
end
In addition, you should probably only run this specific validation rule on: :create -- because it would presumably be totally acceptable for a payment request to become more than the user's balance, later on n the future.
Because self is not what you think it is. In case you didn't know or forgot, validation DSL is just methods called on the class itself. Here you basically call PayoutRequest.validates and pass it some parameters.
validates :amount, numericality: { only_integer: true, greater_than_or_equal_to: 300, smaller_than_or_equal: self.user.balance }
^ ^ arg ^ kw arg ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
method name just a regular hash, defined at the class level. So `self` is the class.
How can I skip validation for nested_attribute if condition is true
aquarium.rb
has_many :fishes
accepts_nested_attributes_for :fishes,
fish.rb
belongs_to :aquarium
validates :ratio, :numericality => { :greater_than => 0 }, if: :skip_this_validation
then in aquariums_controller.rb
def some_action
#aquarium = Aquarium.new(aqua_params)
#aquarium.skip_this_validation = true # i know that this is not valid
#must skip validation for ratio and then save to DB
end
aquarium.rb
has_many :fishes
accepts_nested_attributes_for :fishes,
attr_accessor :skip_fishes_ratio_validation
fish.rb
belongs_to :aquarium
validates :ratio, :numericality => { :greater_than => 0 }, unless: proc { |f| f.aquarium&.skip_fishes_ratio_validation }
then in aquariums_controller.rb
def some_action
#aquarium = Aquarium.new(aqua_params)
#aquarium.skip_fishes_ratio_validation = true
#aquarium.save
end
You can just add the condition in method and check for the conditional validation
class Fish < ActiveRecord::Base
validates :ratio, :numericality => { :greater_than => 0 }, if: :custom_validation
private
def custom_validation
# some_condition_here
true
end
end
#aquarium.save(validate: false)
I believe skips validations on the model.
In Rails 5 you can simply pass optional: true to the belongs_to association.
So in your fish.rb, update association with the following code:
belongs_to :aquarium, optional: true
It will skip association validation if the fish object has no aquarium.
How can I create a validation where committed presence needs to be true only if the challenge's category is habit?
class Challenge < ActiveRecord::Base
CATEGORY = ['goal', 'habit']
serialize :committed, Array
validates :committed, presence: true, if: :habit # I also tried with 'habit' & 'Habit'
end
Since your category is called 'habit' (note, it is not 'Habit'), the validation would look as follows:
validates :committed, presence: true, if: ->(c) { c.category == 'habit' }
As a sidenote: I do not think your scopes will work, unless you have a column called categories in your challenges table.
Thus, if your intention was to select challenges, which have category 'habit', the scope would look as follows:
scope :habit, -> { where(category: 'habit') }
EDIT
As per discussion in comments, if you want committed to be nil instead of [""] when nothing is there, add custom validation:
validate :committed_content
private
def committed_content
self.committed = nil if committed.empty? || committed.all?(&:blank?)
true
end
validates :committed, presence: true, :if => lambda { |c| c.category == 'Habit' }
You can have a method and use it like this:
validates :committed, presence: true, if: :habit?
def habit?
self.category == 'habit'
end
Following the Michael Hartl rails tutorial. Struggling to get the remember token tests to pass, specifically, the test for non-blankness of the remember token.
The code for the User class is below
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
before_save { |user| user.email = email.downcase }
before_save { :create_remember_token }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
and the test I can't get to pass:
subject { #user }
...
describe "remember token" do
before { #user.save }
its (:remember_token) { should_not be_blank }
end
and the error message I get is:
.....................F
Failures:
1) User remember token remember_token
Failure/Error: its (:remember_token) { should_not be_blank }
expected blank? to return false, got true
# ./spec/models/user_spec.rb:120:in `block (3 levels) in <top (required)>'
Finished in 0.68878 seconds
22 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:120 # User remember token remember_token
I don't know if this is relevant but sublime_text isn't doing anything with the self keyword (ie its not highlighting it in a different colour).
I'm using Ruby 1.9.3
The issue is that you're writing before_save { :create_remember_token } when you should have before_save :create_remember_token. The { } is a block. Same as when you do
do
#This is some code
end
That is also a block of code.
That's why your first before_save works, because you're giving the block a piece of code to execute. In the second before_save you're just giving it the name of the method to execute which has the block of code.
Tl:dr:
Change
before_save { :create_remember_token }
to
before_save :create_remember_token
and you should be good to go.
I'm building a simple JSON API using the rails-api gem.
models/user.rb:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :password, :password_confirmation
validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i }
validates :password, presence: { on: :create }, length: { minimum: 6 }
end
When I try to sign up without a password this is the JSON output I get:
{
"errors": {
"password_digest": [
"can't be blank"
],
"password": [
"can't be blank",
"is too short (minimum is 6 characters)"
]
}
}
Is it possible to hide the error message for password_digest? I'm returning the #user object with respond_with in the controller.
I've tried the following but no luck (it just duplicates the error "can't be blank"):
validates :password_digest, presence: false
#freemanoid: I tried your code, and it didn't work. But it gave me some hints. Thanks! This is what worked for me:
models/user.rb
after_validation { self.errors.messages.delete(:password_digest) }
You can manually delete this message in json handler in User model. Smth like:
class User < ActiveRecord::Base
def as_json(options = {})
self.errors.messages.delete('password_digest')
super(options)
end
end