Validating Child Object with ActiveModel Validations - ruby-on-rails-3

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.

Related

Delegate throws error for mongoid document

I have a problem that I don't understand and can't find a solution to:
works:
class Document
CONSTANT_ARRAY = [0,1,2,3]
delegate :sum, to: :CONSTANT_ARRAY
end
does not work:
class Document
include Mongoid::Document
CONSTANT_ARRAY = [0,1,2,3]
delegate :sum, to: :CONSTANT_ARRAY
end
The latter throws error ArgumentError: wrong number of arguments (given 2, expected 1)
To be added, the code was working before the mongoid upgrade, in version ~> 5.0, rails 4, now I have mongoid 7.1.0, rails 5.2.4.1
I'm not sure if it is relevant to add, the code gets called from another class
class Items
include Mongoid::Document
embeds_many :document_fields, class_name: 'Document', cascade_callbacks: true
end
class Another
include Mongoid::Document
embeds_many :items, class_name: 'Item', cascade_callbacks: true
def document_fields
items.flat_map(&:document_fields)
end
end
I have reduced the amount of code in the classes, because I don't see the relevance.
UPDATE: So I've figured out that this works. But is it the right way?
CONSTANT_ARRAY = [0,1,2,3]
delegate :sum => :CONSTANT_ARRAY
logger.debug Document.new.sum # prints 6 as it is supposed to
This is an issue in Mongoid 7.1.0: https://jira.mongodb.org/browse/MONGOID-4849

Null Object Pattern for associations in Rails

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.

Rails nested attributes callback

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

Adding the sum of a has_many relationship to a model's attributes

I have the following (simplified model) and wish to access the 'spent' value in the to_json method of the object, ideally as an attribute of the object.
class Task < ActiveRecord::Base
has_many :hours
def spent
self.hours.sum(:spent)
end
end
Is there a way to do this without defining a method and hacking the to_json method? I've been hunting for a way to use scope or by hacking the after_initialize method, but none of these methods provide a 'spent' value when using inspect or to_json on the model.
I need to solve this on models higher up the tree that use a has_many, through relationship too.
You can use the :methods parameter to to_json call.
object.to_json(:methods => :spent)
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
The best solution I could find to this was overriding the 'as_json' method to include the attributes that I needed, or to perform the logic required, (in this case the sum of the has_many relationship).
class Task < ActiveRecord::Base
...
def as_json(options = { })
options = {} if options.nil?
self[:job_id] = self.phase.job_id
self[:spent] = self.hours.sum(:spent)
super(options)
end
end

Rails 3 Custom Class Question

I am trying to create a separate model class for image uploading, which was previously in the object's controller. I also want to make it agnostic, so I can upload images using one class from multiple objects.
In my original object's model class, I have the following now:
class Object < ActiveRecord::Base
after_save :photo_store
delegate :has_photo?, :photo, :photo_path, :store_photo, :photo_filename, :to => :photo_store
def photo_store
PhotoStore.new(self)
end
end
Then, the PhotoStore class looks like this:
class PhotoStore
attr_reader :object
def initialize(object)
#object = object
end
def photo=(file_data)
unless file_data.blank?
#file_data = file_data
self.extension = file_data.original_filename.split('.').last.downcase
end
end
PHOTO_STORE = File.join RAILS_ROOT, 'public', 'photo_store'
def photo_filename
File.join PHOTO_STORE, "#{id}.#{extension}"
end
def photo_path
"/photo_store/#{id}.#{extension}"
end
def has_photo?
File.exists? photo_filename
end
private
def store_photo
if #file_data
FileUtils.mkdir_p PHOTO_STORE
File.open(photo_filename, 'wb') do |f|
f.write(#file_data.read)
end
end
end
end
However, this throws the error below when I try and use the has_photo? method in the object's view.
undefined local variable or method `id' for #
Do I need to put some other type of relationship in place between the Object and PhotoStore?
And a separate question: What's the best way to make this agnostic? Since it uses just the ID of the object, I could just include the Object's name in the filename, but is that the best way to do it?
Thanks!
Because at File.join PHOTO_STORE, "#{id}.#{extension}" you call method PhotoStore#id, but it does not exists.
You should do that
File.join PHOTO_STORE, "#{#object.id}.#{#object.extension}"