如何从深层嵌套资源中检索相关数据

时间:2014-01-23 12:33:26

标签: ruby-on-rails ruby ruby-on-rails-4 active-model-serializers

我有以下深层嵌套资源:

    resources :venues, shallow: true do
        #Halls
        get "hall/:id/exhibition" => "halls#exhibition", as: :exhibition
        get "hall/:id/visit" => "halls#visit", as: :hall_visit
        get "structure", :to => "venues#venue_structure"
        resources :asset_types, :booths_tags, :tags, :uploaded_files, :events, :chats
        resources :halls do
            resources :webcasts
            resources :booths do
                resources :chats
            end
        end
    end

我想使用events

检索属于某个用户的所有activerecord

我在下面尝试过,但这似乎没有产生我想要的结果是事件数据:

def all_events
    @events = User.joins(:venues => [:events]).where("venues.user_id" => current_user.id).select("events.*, users.*")
    render json: @events
  end

以上生成:

{
users: [
{
id: 1,
email: "eeee",
title: "Mr",
first_name: "aaaa",
last_name: "cccc",
position: "Web Developer",
work_phone: "123456",
company: "aaasszz",
sign_in_count: 60,
last_sign_in_ip: "127.0.0.1",
confirmed_at: "2013-10-29T12:26:00.583+11:00",
created_at: "2013-10-29T12:23:25.453+11:00",
roles: [
3
]
},
{
id: 1,
email: "email",
title: "Mr",
first_name: "aaa",
last_name: "bbb",
position: "Web Developer",
work_phone: "123456",
company: "sss",
sign_in_count: 60,
last_sign_in_ip: "127.0.0.1",
confirmed_at: "2013-10-29T12:26:00.583+11:00",
created_at: "2013-10-29T12:23:25.453+11:00",
roles: [
3
]
}
]
}

我想要JSON中的事件数据......

我也在使用主动模型序列化器。

解决此问题的最佳方法是什么?

活动模型:

class Event < ActiveRecord::Base
  resourcify
  belongs_to :venue

  validates :name, :start, :finish, presence: true

    has_one :event_image, ->{where(:image_type => UploadedFile::IMAGE_TYPE_EVENT_IMAGE)}, as: :imageable, class_name: 'UploadedFile', dependent: :destroy
    has_one :logo1, ->{where(:image_type => UploadedFile::IMAGE_TYPE_EVENT_LOGO1)}, as: :imageable, class_name: 'UploadedFile', dependent: :destroy
    has_one :logo2, ->{where(:image_type => UploadedFile::IMAGE_TYPE_EVENT_LOGO2)}, as: :imageable, class_name: 'UploadedFile', dependent: :destroy
    accepts_nested_attributes_for :event_image, :logo1, :logo2, :reject_if => proc { |attributes| attributes['assets'].blank? }

end

1 个答案:

答案 0 :(得分:0)

路由对于从数据库中检索记录并不重要。这里唯一重要的是模型。您可以使用the includes method from ActiveRecord包含相关对象。因为您最终需要事件,所以只需从事件模型启动查询。这是我能想到的最简单的解决方案:

Event.includes(:venue).where(:venues => {:user_id => current_user.id})

如果您不需要场地数据,请使用joins

Event.joins(:venue).where(:venues => {:user_id => current_user.id})