I want to create a model called 'Persona' (which belongs_to model User). The user chooses a name in a form and then clicks the create button, so I need the attribute 'name' in the Persona model. I also want the Persona model to have a lower case version of the persona's name, so I need a second attribute 'downcase_name'. For example, the user may choose the persona's name to be Fooey Barman, so the downcase_name would be fooey barman.
My questions is, how do you initialise the downcase_name attribute? Do you put it in the Persona controller? In the new or create methods? Something like:
def create
#persona = Persona.new(persona_params)
#persona.downcase_name = #persona.name.downcase
if #persona.save
flash[:success] = "Welcome, " + #persona.name
redirect_to #persona
else
render 'new'
end
end
Or do you put it in the model?
class Persona < ActiveRecord::Base
before_create :make_downcase_name
validates :name, presence: true, length: { maximum: 50 }
private
def make_downcase_name
self.downcase_name = name.downcase
end
end
Or perhaps like this?
class Persona < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
validates :downcase_name, presence: true
end
EDIT:
So, am I right in thinking the way to do it is in the model, with a before_save and a validation, like this?:
class Persona < ActiveRecord::Base
before_save :make_downcase_name
validates :name, presence: true, length: { maximum: 50 }
validates :downcase_name, presence: true
private
def make_downcase_name
self.downcase_name = name.downcase
end
end
The use of the before_* callback seems pretty idiomatic. Alternatively, you can also have a service object created in the controller (say PersonaCreator) that would handle the logic and set the appropriate attributes on the model.
Note that before_create will be called only once, meaning that if the user changes the persona's name later, the callback will not be called. You might want to do something like before_save and check whether the name has been changed.
Related
I've some Active Record validations on my model:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
end
That seems fine. It validates that the field name is not nil, "" and that it must have exactly 10 characters. Now, if I want to add a custom validation, I'd add the validate call:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_must_start_with_abc
private
def name_must_start_with_abc
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
end
The problem is: when the name field is nil, the presence_of validation will catch it, but won't stop it from validating using the custom method, name_must_start_with_abc, raising a NoMethodError, as name is nil.
To overcome that, I'd have to add a nil-check on the name_must_start_with_abc method.
def name_must_start_with_abc
return if name.nil?
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
That's what I don't wan't to do, because if I add more "dependant" validations, I'd have to re-validate it on each custom validation method.
How to handle dependant validations on Rails? Is there a way to prevent a custom validation to be called if the other validations haven't passed?
I think there is no perfect solution unless you write all your validations as custom methods. Approach I use often:
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_custom_validator
private
def name_custom_validator
return if errors.include?(:name)
# validation code
end
end
This way you can add as many validations to :name and if any of them fails your custom validator won't execute. But the problem with this code is that your custom validation method must be last.
class Product < ApplicationRecord
validates :name, presence: true, length: { is: 10 }
validate :name_must_start_with_abc, unless: Proc.new { name.nil? }
private
def name_must_start_with_abc
unless name.start_with?('abc')
self.errors['name'] << 'must start with "abc"'
end
end
end
Please check allow_blank, :allow_nil and conditional validation as well for more options.
I have a model "User" with attribute "Username". Can I use validations to prevent a User being created with the Username "home"?
class User < ActiveRecord::Base
validates :username, presence: true
end
You can use an exclusion validator:
class User < ActiveRecord::Base
USERNAME_BLACKLIST = ['home'].freeze
validates :username, presence: true, exclusion: { in: USERNAME_BLACKLIST }
end
Alternatively, you can always rely on a custom validation method, using validate instead of validates, for more complex types of validation that aren't easily expressed using built-in validators:
class User < ActiveRecord::Base
validates :username, presence: true
validate :username_not_on_restricted_list
protected
def username_not_on_restricted_list
errors.add(:username, :invalid) if username == 'home'
end
end
You could also write a custom validator if you intend to reuse this functionality across multiple models.
I'm building instances of a model in another model controller. All seems to work fine, child instances are well created with the parent id but as soon as I add validations for parent_id in this resource, the instance is no longer valid. Any idea what I'm missing ?
Mission model:
class Mission < ActiveRecord::Base
has_many :planned_times
validates :code, presence: true, uniqueness: { case_sensitive: false }
validates :days_sold, presence: true
end
PlannedTime model:
class PlannedTime < ActiveRecord::Base
belongs_to :mission
validates :date, presence: true
validates :mission_id, presence: true # this is the validation which causes problem
end
Mission controller:
class MissionsController < ApplicationController
def create
#mission = Mission.new(mission_params)
week_nums = params[:weeks].split(/[\s]*[,;\-:\/+][\s]*/).uniq
year = params[:year].to_i
week_nums.each do |week_num|
date = Date.commercial(params[:year].to_i,week_num.to_i)
#mission.planned_times.build(date: date)
end
if #mission.save
flash.now[:success] = "Mission added"
end
end
private
def mission_params
params.require(:mission).permit(:code, :days_sold)
end
end
So validating the presence of associations is a little tricky. In your case you're putting the mission_id validator on the child association but rails runs the validation on planned_time before it saves the mission so it will fail because mission_id is still nil. Also, by putting the validation on planned_time it'll mean that that validation won't run if you never mission.planned_items.build because the associated planned_time won't exist and therefore not run its validations.
With minimal changes to your code or validation logic you can get it to work like this:
class PlannedTime < ActiveRecord::Base
belongs_to :mission
validates :mission_id, presence: { if: ->(p) { p.mission.nil? } }
end
This part presence: { if: ->(p) { p.mission.nil? } } will check if there is a mission object present (albeit without an id yet) and if there is no mission object the validation will fail. So good, now we know we can't create a planned_time without its parent mission object present. But this says nothing about the mission requiring the planned_time to be created. If this is what you want then that's the solution. Although I'm left wondering if you really wanted it the other way around where you want to make sure a mission is always created along with its planned_time?
My app allows users to add words from a master words table into their own custom list. So, a word list contains multiple custom words each of which link to a master word.
In my view, I have a field called word_text (virtual attribute) where I let users enter a word, and in my model I am trying to look up the master_word_id and set it on the custom word table. I am unable to access the #word_text value in the model. I always seem to get an error that the master word is a required field (because the look up is failing).
class CustomWord < ActiveRecord::Base
attr_accessible :master_word_id, :word_list_id, :word_text
attr_accessor :word_text
belongs_to :word_list
belongs_to :master_word
validates :word_list, presence: true
validates :master_word, presence: true
before_validation :set_master_word
private
def set_master_word
logger.debug "Received word text #{#word_text}"
_mw_id = nil
if !#word_text.nil?
master_word = MasterWord.find_word(#word_text)
if master_word.nil?
errors.add("#{#word_text} is not a valid word")
else
_mw_id = master_word.id
end
end
self.master_word_id = _mw_id
end
end
I sincerely appreciate any suggestions as to how I can set the value of the master_word_id correctly.
There are several things to fix:
class CustomWord < ActiveRecord::Base
attr_accessible :master_word_id, :word_list_id, :word_text
attr_accessor :word_text
belongs_to :word_list
belongs_to :master_word
validates :word_list, presence: true
#validates :master_word, presence: true <= This will always throw error
validates :word_text, presence: true
validates :master_word_id, presence: true
before_validation :set_master_word
private
def set_master_word
logger.debug "Received word text #{self.word_text}"
self.master_word_id = MasterWord.find_by_word_text(self.word_text).id
end
end
Not sure if it will work because I don't know the rest of your app but I hope it points you in the right direction.
I'm having hard time with this, it's not a direct problem of implementation but I don't understand which is the right way to do it, I have two options, but first, these are my models:
class Boat < ActiveRecord::Base
validates :name, presence: true, uniqueness: { case_sensitive: false }
has_many :tech_specs, order: 'position'
def visible?
self.visible
end
end
class TechSpec < ActiveRecord::Base
validates :boat_id, presence: true
validates :tech_spec_name_id, presence: true, uniqueness: { scope: :boat_id }
belongs_to :boat
belongs_to :tech_spec_name
before_destroy :destroy_name_if_required
acts_as_list scope: :boat
def as_json(options = {})
super(options.except!(:tech_spec_name_id).merge!(methods: [self.name]))
end
def name
self.tech_spec_name.try(:name) || ''
end
def name=(value)
self.tech_spec_name = TechSpecName.find_or_create_by_name(value)
end
def destroy_name_if_required
self.tech_spec_name.destroy if self.tech_spec_name.tech_specs.size <= 1
end
end
class TechSpecName < ActiveRecord::Base
validates :name, presence: true, uniqueness: { case_sensitive: false }
has_many :tech_specs
def self.with_name_like(str)
where('lower(name) LIKE lower(?)', "%#{ str }%")
end
end
The problem is that I want a page for a boat showing some tech specs when with a locale and when on a different locale, showing other tech specs.
Idea #1
My basic idea is to add to TechSpec globalize3 on tech_spec.value and on TechSpecName for field tech_spec_name.name
Idea #2
The other idea is to remove TechSpecName and, instead, use a field (tech_spec.name) that will "replace" completely TechSpecName. Notice that in this case, I'll still need to fetch names for autocomplete, but I will filter them in TechSpec instead of fetching all from TechSpecName. This field will use globalize3 again obviusly.
I don't know the downside of both approaches, so I need a suggestion.
Seems like idea #1 is ok, it works correctly and reduce the amount of repeated text inside Db.
I18n.with_locale helps a lot too, also Globalize.with_locale is helpful