Joy
Joy

Reputation: 4483

Function for populating a model data with another model

I am new to Rails. I have written two models A and B. Models of A and B are like following:

 class A < ActiveRecord::Base
   attr_accessible: a1, a2
 end

 class B < ActiveRecord::Base
   attr_accessible: b1,b2
   self.table_name = "b"
 end

Actually here there is a rake task that will populate the data of A with data of B on daily basis so that from the rake task we can call the function. I cannot understand where to write those functions that will populate the data of A with data from B.

Upvotes: 1

Views: 125

Answers (1)

MurifoX
MurifoX

Reputation: 15089

You have mentioned that there are some rake tasks. You can put the code inside them, on lib/tasks directory. As an example:

copy_from_b_to_a.rake

namespace :copy do
  task :from_b => :environment do
    B.all.each do |b|
      a = A.new a1 => b1, a2 => b2
      a.save
    end
  end
end

If you run rake -T, you can see rake copy:from_b listed as a task, and when you run it, it would try to copy the data executing the code inside the .rake task you created.

That's just a simple example of working with rake tasks.

Upvotes: 1

Related Questions