Topic: Database update with has_many relationship

I need to do an update on my database where an Project has_many :costs. If there is a cost with :year equal to 0 I need to set :old_cost in Project to the value of :cost in the Cost.

That sounds like garbage so time for some code.

class Project
    has_may :costs

class Cost
    belongs_to :project

I have tries looking at update_all but that didn't seem suitable for this and I tried looping through projects and then costs in the rails console and doing an if inside that but the resulting SQL was just a SELECT not and UPDATE.

Thanks for any help

Re: Database update with has_many relationship

Try this:

Cost.where(:year => 0).each do |cost|
  cost.project.update_attribute(:old_cost, cost.cost)

Find the costs with year 0, then update the cost's product's old_cost with the associated cost's cost.
If you need less queries, you can work with:

Cost.where(:year => 0).include(:project)

Re: Database update with has_many relationship

I used the top one and it worked beautifully, thank you.

I was a bit confused about the bit at the bottom (I'm new to this). Could you show me it in an example and explain a bit about what the include does, I couldn't find any documentation.