【问题标题】:ActiveRecord get all + associated detailsActiveRecord 获取所有+相关的详细信息
【发布时间】:2015-02-07 20:39:16
【问题描述】:

我正在尝试检索所有任务的列表,其中每个任务都有一个开发人员和审阅者。我能够检索列表,但它包含 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的后续问题。

【问题讨论】:

    标签: ruby activerecord sinatra


    【解决方案1】:

    经过一番搜索发现as_json(include: &lt;association&gt;) 所以这行得通

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

    但需要考虑其他替代方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      相关资源
      最近更新 更多