Is creating an association entry unobtrusive when trying to access?

I have a simple has_one / belongs to the relationship between the two models.

This is a new association in my application, so there are many records that have not yet created a related record.

In my application, I assume that the model has an association, and I get access to its attributes and methods. However, since the association does not exist, I encounter many errors.

What I would like to do is to unobtrusively create a linked record on the fly whenever she first gets access to any of her methods and attributes. It doesn't matter what the data is in the record, I just need it to exist, so the methods that I call can create the data.

Edit: I don’t want to check and create a record in all instances where I try to access relationships, so this is an ideal solution for the model itself, and not in my controllers anywhere.

Any thoughts?

Thanks!

+3
source share
4 answers

Here's what we ended up doing with it. I did not write this (employee), but it passes the previously unsuccessful tests that I wrote for this case.

def stats_with_create
  stats_without_create || create_stats
end
alias_method_chain :stats, :create
+1
source

In the controller, you can put something like this in a method show(untested, but it should give you an idea:

@thing = Thing.find params[:id]
if @thing.other_thing.nil?
  @thing.other_thing = OtherThing.new.save!
  @thing.save!
end

, , , , Thing, , .

, other_thing, .

, , , , , , .

0

. , , , , .

.

0

I have done this before, but not at the model level. Ive done this at the controller level using before_filter, which ran before all methods that needed access to a model association that did not exist or did not exist.

I just realized that after_find and after_initialize callbacks can be used in the model.

You can stick with:

def after_initialize
   association.build if association.nil?
end

in your model and it should solve your problems .. (disclaimer: not verified by me) :)

0
source

Source: https://habr.com/ru/post/1708765/


All Articles