Despite looking at a few answers here regarding Null Objects in rails, I can't seem to get them to work.
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
def profile
self.profile || NullProfile #I have also tried
#profile || NullProfile #but it didn't work either
end
end
class NullProfile
def display #this method exists on the real Profile class
""
end
end
class UsersController < ApplicationController
def create
User.new(params)
end
end
My problem is that on User creation, I pass in the proper nested attributes (profile_attributes) for the Profile and I end up with a NullProfile on my new User.
I am guessing that this means that my custom profile method is getting called on create and returning a NullProfile. How do I do this NullObject properly so that this only happens on read and not on the initial creation of the objects.
I was going exactly through and I wanted a clean new object if it wasn't present(if you're doing this just so object.display doesn't err maybe object.try(:display) is better) this too and this is what I found:
1: alias/alias_method_chain
def profile_with_no_nill
profile_without_no_nill || NullProfile
end
alias_method_chain :profile, :no_nill
But since alias_method_chain is being deprecated, if you're staying on the edge you would have to do the pattern by yourself manually... The answer here seems to provide the better and more elegant solution
2(Simplified/practical version from the answer):
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
module ProfileNullObject
def profile
super || NullProfile
end
end
include ProfileNullObject
end
note: The order you do this matter(explained in the linked answer)
On what you tried:
When you did
def profile
#profile || NullProfile
end
It won't behave as expected because the Association is lazily loaded(unless you told it to :include it in the search), so #profile is nil, that's why you're always getting NullProfile
def profile
self.profile || NullProfile
end
It will fail because the method is calling itself, so it's sort like a recursive method, you get SystemStackError: stack level too deep
I've found a simpler option than including a private module in the accepted answer.
You can override the reader method and fetch the associated object using the association method from ActiveRecord.
class User < ApplicationRecord
has_one :profile
def profile
association(:profile).load_target || NullProfile
end
end # class User
Instead of using alias_method_chain, use this:
def profile
self[:profile] || NullProfile.new
end
According to the Rails docs, the association methods are loaded into a module, so it's safe to override them.
So, something like...
def profile
super || NullProfile.new
end
Should work for you.
Related
I have two plain Ruby classes, Account and Contact. I am using Simple Form's simple_form_for and simple_fields_for to create nested attributes. I am looking to fulfill the following validation requirements:
An associated Contact must exist for the new Account
The associated Contact must be valid (i.e., account.contact.valid?)
It looks like ActiveModel no longer includes the validates_associated method, as using that method results in an undefined method error. I considered requiring ActiveRecord::Validations, but this led down a stretch of various errors (e.g., undefined method `marked_for_destruction?')
I also considered defining validate on the Account class and calling valid? on the associated object, but that only prevented the form from submitting if there was also an error on the parent object.
validate do |account|
account.contact.valid?
# required for form to fail
errors.add(:base, "some error")
end
Is there something I'm not aware of to solve this? Thanks.
I recently (7 years after this question has been asked!) faced the same issue and solved it by implementing the AssociatedValidator based on the ActiveRecord one.
I simply included it in config/initializers folder:
module ActiveModel
module Validations
class AssociatedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if Array(value).reject { |r| valid_object?(r) }.any?
record.errors.add(attribute, :invalid, **options.merge(value: value))
end
end
private
def valid_object?(record)
record.valid?
end
end
module ClassMethods
def validates_associated(*attr_names)
validates_with AssociatedValidator, _merge_attributes(attr_names)
end
end
end
end
now you can use validates_associated in ActiveModel too.
class Person
include Virtus
include ActiveModel::Model
attribute :address, Address, :default => Address.new
validate :address_valid
private
def address_valid
errors.add(:base, 'address is not valid') unless address.valid?
end
end
class Address
include Virtus::ValueObject
include ActiveModel::Validations
attribute :line_1, String
attribute :line_2, String
validates :line_1, :presence => true
validates :line_2, :presence => true
end
The errors show up in the form if you pass an object to simple_fields_for:
= form.simple_fields_for person.address do |af|
= af.input :line_1
Another option is overriding valid?:
def valid?
super & address.valid?
end
Note its & not && so the conditions are not short circuited if the first returns false.
I've two models
class Article < ActiveRecord::Base
has_one :review
end
class Review < ActiveRecord::Base
belongs_to :article
end
Now I would like to have this method in Article
class Article < ActiveRecord::Base
has_one :review
def self.has_review?
end
end
I've tried with .count, .size....but I've errors...how can I do to have the following code working
#article = Article.find(xxx)
if #article.has_revew?
....
else
...
end
The reason why I need it is becaus I will have different action in views or controller, if there is one Review or none
Regards
class Article < ActiveRecord::Base
has_one :review
def has_review?
!!review
end
end
This just defines a method on the instance (def self.method defines a class method). The method tries to load review. If the review does not exist, it will be nil. !! just inverts it twice, returning true if a review exists or false if the review is nil.
Right now I'm working on a Rails app that has an Event model and this model has Category models as nested attributes.
My Event model has a state attribute which must change to certain value if it's nested categories reach a particular amount.
I tried to do this using the after_update callback in the Event model, but it didn't work. Does anyone have any idea?
Why it didn't work? Probably because it reached maximal recursion level.
Try something like this:
class Event < ActiveRecord::Base
attr_accessor :category_count_state_updated
has_many :categories
accepts_nested_attributes_for :categories
attr_accessible :categories_attributes
after_update :update_state
private
def update_state
unless self.category_count_state_updated
self.state = 'categories_count_reached' if self.categories.count == 5
self.category_count_state_updated = true
self.save
end
end
end
I want to put logic in the model rather than controller.
class UsersController < ApplicationController
def somemethod
d = User.methodinmodel
end
end
class User < ActiveRecord::Base
def methodinmodel
"retuns foo"
end
end
I get an error that there is no methodinmodel for the User model.
Why?
If you want to be able to call methodinmodel on the User class in general rather than a specific user, you need to make it a class method using self:
class User < ActiveRecord::Base
def self.methodinmodel
"returns foo"
end
end
Your current method definition would only work if you called it on a user:
#user = User.create!
#user.methodinmodel # Works.
User.methodinmodel # Doesn't work.
Using the new implementation using self would allow you to call it like:
User.methodinmodel # Works.
on a previous question, I was searching for a way to
dynamic valitating my models.
Advice on "Dynamic" Model validation
The solution that I got working is:
def after_initialize
singleton = class << self; self; end
validations = eval(calendar.cofig)
validations.each do |val|
singleton.class_eval(val)
end
end
On my actual app, I have 2 models
class Calendar < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :calendar
def after_initialize
singleton = class << self; self; end
validations = eval(calendar.cofig)
validations.each do |val|
singleton.class_eval(val)
end
end
end
As you can see, the validation code that should be added to the Event class lies on the Calendar field "config".
Works fine for a existing Event, but doesn't for a new record. That's because, at the time that after_initialize is called, the association doesn't exists yet.
I can't find a way to do that besides putting the config values on Event itself.
Any advices?
Tks!
You probably want to run your validation code during the validation phase, not the initialize phase. Try this:
class Calendar < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :calendar
validate do |event|
validations = eval(calendar.cofig)
validations.each do |val|
eval(val)
end
end
end