Invalidating parent model save through child before_save callback - ruby-on-rails

I have two models, a Parent and a Child (as outlined below). The child model has a before_save callback to handle some external logic, and if it encounters any errors, the callback invalidates that model being saved.
class Parent < ActiveRecord::Base
has_one :child
accepts_nested_attributes_for :child
validates :child, :presence => true
validates_associated :child
end
class Child < ActiveRecord::Base
belongs_to :parent
before_save :external_logic
validates :parent, :presence => true
def external_logic
begin
# Some logic
rescue
#Invalidate child model
errors.add(:base, "external logic failed")
return false
end
end
end
The problem that I'm running into is that the Child model instance is created as through the nested attributes of the Parent model. When the external logic fails, I want the child model AND the parent model to not be saved, but instead the parent model is being saved on its own. How can I achieve this?
Please note, I am aware of validation callbacks, but they are not suitable in this case. The child model callback has to be a before_save.
EDIT #1
I already know about transactions, and don't consider someone telling me "hey, wrap it around a transaction externally" to be a valid response. This question is explicitly about how to solve this issue through a before_save call.
Why I can't use validations on create - as mentioned in the comments, the external bit of logic needs to be guaranteed to run ONLY before a database save. Validation calls can happen multiple times with or without altering the database record, so that's an inappropriate place to put this logic.
EDIT #2
Ok, apparently having the before_save return false does prevent the parent being saved. I have verified that through the console and actually inspecting the database. However, my rspec tests are telling me otherwise, which is just odd. In particular, this is failing:
describe "parent attributes hash" do
it "creates new record" do
parent = Parent.create(:name => "name", :child_attributes => {:name => "childname"})
customer.persisted?.should be_false
end
end
Could that be an rspec/factory_girl bit of weirdness?
EDIT #3
The test error is because I'm using transactional fixtures in Rspec. That was leading to tests that incorrectly tell me that objects were being persisted in the database when they really weren't.
config.use_transactional_fixtures = true

Okay so your problem is with the ActiveRecord::Callbacks order.
As you can see on the linked page first validation is processed and if validation was successful then before_save callbacks are run. before_save is a place where you can assume every validation passed so you can manipulate a bit data or fill a custom attribute based on other attributes. Things like that.
So what you could do is just say for the Child model:
validate :external_logic and just remove the before_save :external_logic callback.
It's equivalent with what you want to do. When a Parent instance is created it will just error out if the Child object fails to validate, which will happen in your :external_logic validation method. This is a custom validation method technique.
After OP update:
Still you can use :validate method. You can set it to only run on create with:
validate :external_logic, :on => :create.
If you are running into issue that you need this to run on update as well, that is the default behavior. Validations are run on .create and .update only.
OR If you want to stick to before_save:
The whole callback chain is wrapped in a transaction. If any before callback method returns exactly false or raises an exception, the execution chain gets halted and a ROLLBACK is issued; after callbacks can only accomplish that by raising an exception.
I see you did return false so it should work as expected. How do you use Parent.create! method? What are the arguments there?
Make sure you are using it like (supposing .name is an attribute of Parent and Child):
Parent.create!{
:name => 'MyParent'
# other attributes for Parent
:child_attributes => {
:name => 'MyChild'
# other attributes for Child
}
}
This way it both the Parent and Child object will be created in the same transaction, so if your before_save method returns false Parent object will be rolled back.
OR
If you cannot use this format you could just try using pure transactions (doc, example in guides):
Parent.transaction do
p = Parent.create
raise Exception if true # any condition
end
Anything you do inside of this transaction will be rolled back if there is an exception raised inside the block.

Related

Rails 6 gem client_side_validations applied to a model with context not working

I have a model like this:
class Profile < ApplicationRecord
validates :username, presence: true, on: :data_setup
end
where :data_setup is a page.
After installing the client side validation gem, it won't work, unless I erase the context part on: :data_setup
Is there any way to make it work?
Your expectations for this are completely wrong. Models are not aware of the request, controller or anything else really outside the the model unless you explicitly pass it in or its a global.
For validations on: is most commonly used to restrict the validation to the create or update contexts. Note that this has nothing to do with what "page" you are on - the context is just tied to if the model instance is a new record or not.
When using custom contexts you need to manually trigger it by passing the context to valid?, invalid? or save:
Profile.new(username: nil).valid? # true
Profile.new(username: nil).valid?(:data_setup) # false

Why does a child model failing validation on destroy blow up accepts_nested_attributes_for?

We have an accepts_nested_attributes_for with a dependent: destroy that works fine with the _destroy param arg.
We added a validation on the child, and that works as expected.
But when we combine the two the save on the parent throws an unhandled error instead of returning false.
class Foo < ActiveRecord::Base
accepts_nested_attributes_for :bars, allow_destroy: true
...
end
class Bar < ActiveRecord::Base
before_destroy :can_do?
def can_do?
unless yeah_sure
errors.add(:base, I18n.t("the.translation"))
false
end
end
...
end
The bar_spec tests yeah_sure in both cases, with errors being empty or present (and the correct message is in there).
When I stepped through the rails portion there are 3 levels of catch, rollback/cleanup, and release in active_support and transaction.
I also tried to rescue in the controller, both method level and a begin block, and neither of those trapped the error, which is strange.
Any idea why foo.save is throwing an error instead of returning false?
Rails 4.2.10
You can use the inverse_of to run the validation on nested attributes.
Also, you can reject the attributes using reject_if block
please refer the following link.

Why does adding a bang make create work?

Rails convention of adding a bang to the end of a method makes it throw an exception if it fails. But my experience isn't matching that behavior.
My controller for a many-to-many relationship (an audit trail). The relationship object cannot be created, only updated by posting events to the audit trail object. (Which means you create by updating...)
I have a User object and a Foo object I'll call the relationship Bar.
bar=Bar.where(:user_id=>params[:user_id]).where(:foo_id=>params[:foo_id]).first
if bar
authorize! :update, bar
else
user=User.find(params[:user_id])
authorize! :bar_create, user
foo=Foo.find(params[:foo_id])
bar=Bar.create!(:user_id=>user.id, :foo_id=>foo.id)
end
The create method does not work. I debugged, and bar.save worked fine, but the entire point of create is to avoid having to make that second call to save. I experimented, and discovered that create! works just fine.
Edit:
As I continued on, I discovered that create! did not, in fact, always save. No errors in the underlying object, just mysteriously not saved.
I've had to do a create call followed by a save call, which... honestly, I just don't understand.
Edit: Per request, adding model code -- simplified to the relevant statements by removing unnecessary methods, validation calls, and the like. (While writing this, I noticed that I haven't yet added the has_many :through calls, but... doesn't seem like those should be relevant to the issue at hand.
class User < ActiveRecord::Base
has_secure_password
has_many :progresses
end
class Bar < ActiveRecord::Base
belongs_to :user
belongs_to :foo
has_many :bar_events
validates :user, :presence=>true
validates :foo, :presence=>true
scope :user_id, -> (user_id){ where user_id: user_id}
scope :foo_id, -> (foo_id){ where foo_id: foo_id}
end
class Foo < ActiveRecord::Base
end
There is a validation error or more in one of the associations in Bar foo or user. Try inspecting those objects:
bar=Bar.create!(:user_id=>user.id, :foo_id=>foo.id)
puts bar.errors.inspect, bar.user.errors.inspect, bar.foo.errors.inspect
That will print the errors of all those objects to the terminal running rails server. The only reason create would not save is due to validation errors in itself or nested associations.

Why doesn't my custom validation run in Rails?

This is my model:
class Goal < ActiveRecord::Base
belongs_to :user
validate :progress_is_less_than_max
private
def progress_is_less_than_max
if progress > max
errors.add(:progress, "should be less than max")
end
end
end
If I go into the console and do
some_user.goals.create! :name => 'test', :max => 10, :progress => 15, :unit => 'stuff'
it saves just fine, without any errors. What am I not doing right?
Well, that's not how you write a custom validator: your custom validator should inherit from ActiveModel::EachValidator.
See the bottom of this rails cast for an example of a customer validator: http://railscasts.com/episodes/211-validations-in-rails-3?view=asciicast
#jaydel is correct in that .create will return an instance of the model (regardless of if it is saved in the database or not).
Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
However, calling .save! on the .create'd model or calling .create! to begin with will raise an exception if validations fail.
Creates an object just like ActiveRecord::Base.create but calls save! instead of save so an exception is raised if the record is invalid.
.save will run validations but returns false if they fail.
By default, save always run validations. If any of them fail the action is cancelled and save returns false. However, if you supply :validate => false, validations are bypassed altogether. See ActiveRecord::Validations for more information.

Calling valid? on new records, but ignore validity of built associations

I have three tables: tasks, departments, and department_tasks. I need to call "valid?" on new task objects, but I want to ignore the validity of any "built" department_tasks. We are doing bulk uploads, and so we load everything or nothing.
As we loop through the Excel file we are reading in, we build the new "Task" according to the values in each row. With each row, there may be an associated department for the task; if there is, we "build" the associated department_task object like so:
new_task.department_tasks.build(:department_id => d.id)
At the end of the loop, we test the validity of the new "task" object by calling "valid?"
new_task.valid?
If the task is valid, it goes in the "good" pile; if it's bad, it goes on the "bad" pile.
The problem is, we haven't saved the task and therefore it has no :id. Without an id, the "built" department_task is invalid (:department_id and :task_id must both be present).
I need to know how I can call "valid?" or test validity of the "new_task" object without the validation cascading down to the "task_department" associated object which cannot be valid before task is saved.
You can skip individual validations using :if or :unless
validates_presence_of :department_id,
:unless => lambda { |record| record.new_record? }
If I understand correctly, you have something like this:
class Task < ActiveRecord::Base
has_many :department_tasks
has_many :departments, :through => :department_tasks
validates_associated :department_tasks
end
class DepartmentTask < ActiveRecord::Base
belongs_to :task
belongs_to :department
validates_presence_of :department_id, :task_id
end
When Task is new the associated validation in DepartmentTask fails because task_id is nil. Correct?
I don't see an easy way around this. The most obvious solution is to just remove the validates_presence_of for task_id. If the only way that you create DepartmentTasks is to build them through the Task model, the presence_of validation seems unnecessary, since Rails will always add the task_id when Task is saved.
Another option is to wrap it in a transaction, create the new task (so it has an ID), then build and validate DepartmentTask, and rollback if invalid.
You should assign an object to your AR queries to check it's validity, also use .new(:department_id => d.id)
myrecord = new_task.department_tasks.new(:department_id => d.id)
if myrecord.save!
"good pile"
else
"bad pile"
end

Resources