Question

Here is my question. I have 2 associated Datamapper models:

class Task
 include DataMapper::Resource
 property :id,           Serial
 property :date,         Date
 property :amount,       Float 

 belongs_to :project,   :required => true
end

class Project
 include DataMapper::Resource
 property :id,          Serial
 property :name,        String,  :required => true
 property :desc,        Text

 belongs_to :company
 has n, :tasks
end

My goal is to created JSON that will contain task date, amount and project name, that should be matched by project_id. At the moment JSON generation has following look:

Task.all.to_json(:only => [:date, :amount, :project_id])

I can access project_id from Task model, but have no idea how to add respective project name from Project model for every task. In SQL it looks like join:

select tasks.date, tasks.amount, projects.name from tasks
inner join projects
on tasks.project_id = projects.id;

Can you suggest correct way to create final JSON, using Datamapper way, but not SQL?

Thank you.

Was it helpful?

Solution

I have found solution for my problem. Here it is:

# create new structure to store merged result
Task_entry = Struct.new(:date, :amount, :pname)

# array to get results from database
all_task_items = Array.new

# run through result and fill the array with required data
Task.all.each do |task|
  task_item = Task_entry.new(task.date, task.amount, task.project.name)
  all_task_items << task_item
end
all_task_items.to_json # generate json

It works for me well. Hope it can be helpful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top