ActiveRecord获取所有+相关详细信息

时间:2015-02-07 11:43:13

标签: ruby activerecord sinatra

我正在尝试检索所有任务的列表,其中每个任务都有开发人员和审阅者。我能够检索列表,但它包含developer_id和reviewer_id。如何检索包含开发人员名称和检索者名称的列表?

class Person < ActiveRecord::Base
end

class Unread_Object < ActiveRecord::Base
  belongs_to :person
end

class Developer < Person
  has_many :tasks 
end
class Reviewer < Person
  has_many :tasks
  has_many :unread_objects
end

class Task < ActiveRecord::Base
  belongs_to :developer
  belongs_to :reviewer
  has_many :documents
  after_save :add_task_to_unread_objects

  protected
    def add_task_to_unread_objects
      Person.find_each do |person|
        Unread_Object.create(
                              :person_id => person.id,
                              :internal_object_id => self.internal_object_id,
                              :unread_cause => 'Create')
      end
    end
end

我尝试过的事情。

get '/taskslist' do
  #Task.includes([:developer, :reviewer]).all.to_json
  #Task.joins(:developer,:reviewer).select("tasks.*, people.*").to_json #works somewhat but only shows one name
  #Task.includes(:reviewer.name,:developer.name).all.to_json #"undefined method `name' for :reviewer:Symbol"
  #Task.find(:all, :include => {:people => :name}).to_json #Couldn't find all Tasks with 'id': (all, {:include=>{:people=>:name}}) 
end

我希望为开发人员,审阅者和其他对象提供嵌套json的Tasks json。 这个问题是对this

的跟进

1 个答案:

答案 0 :(得分:0)

经过一番搜索后发现as_json(include: <association>) 所以这个工作

Task.includes(:developer,:reviewer).all.as_json(include: [:developer,:reviewer]).to_json

但还需要看到其他替代方案。