ruby on rails - Method to change resource attribute based on nested resource attributes -
I've got a Rail 4 app quite a simple question; I have written a method, but I do not know where it should go and how to call it.
I have a resource, targets
, and nested resources, work
(i.e. the tasks of each goal) all work well.
What I want to do is set so that work
is target
for each task
is correct Converts the
position
of the target
The method I want to use is the content:
complete = true @ goal.tasks.each do | T | if! T.Stats? Complete = Ending the wrong end if completed? @ Goal.status = true end
Checks if there is status
in the work of all targets
: and if That is, also changes the status
to targets
.
My idea is to put that method in the target
. Model, but as far as I can guess.
- Where does the method go? (Is this a model like I thought?)
- How do I call the method (/ what do I need)?
(I know the method may contain some minor syntax errors, but once I can actually use it, I will be able to test and trigger it !)
Thank you for taking the time to see someone.
You can simplify your function as follows:
@ Goal.status = @ goals.tasks.map (& amp;: complete). All?
Assume that you want to know as soon as possible that your target
is complete, you can assign this function to your task
Models You can do it as follows:
def task < ActiveRecord :: Base is_to: target after_save: goal_completed def goal_completed if self.goal.tasks.map (& amp; complete). all? Self.goal.update_attribute (full, true) end and end
As you can see, if you have many tasks
a target For
, this can be very expensive quickly, because you are pulling task
each time a target
's work
. Therefore, for a large database, I advised to count the entire work for each goal (it really is similar to what is being implemented in a project like me.)
For, you have to add a counter cache column to your goals
for target
taskkit
(if you have not already), and target < Add another column called
completed_tasks_count
to / code> Or something like that. Make sure they omit both of them.
def target & lt; ActiveRecord :: Base is has_many: work, inverse_of :: target, counter_cache: true end def work < ActiveRecord :: Base is_to: target, inverse_of :: task after_initial: set_completed_tasks_count, on: new around_save: goal_complete def set_completed_tasks_count self.completed = false if self.new_record? & Amp; & Amp; Self.completed.nil? Self.completed if end DEF yields goal_complete? & Amp; & Amp; ! Self.completed_wasself.review.increment! (: Completed_tasks_count) Elsf (! Self.completed? & Amp; amp; amp; and self.completed_was) || Self.marked_for_destruction? Self.review.decrement! (: Completed_tasks_count) End End End
Hope this helps Happy Coding!
Comments
Post a Comment