Question

I have deeply nested resources below:

    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

I want to retrieve all events rows that belong to a certain user using activerecord

I tried below but this doesn't seem to be generating results that I want which is event data:

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

above generates:

{
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
]
}
]
}

I want events data in JSON instead...

I'm also using active model serializers.

What is the best approach for this problem?

Event Model:

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
Was it helpful?

Solution

The routes are not important for the retrieval of the records from the database. The only thing that matters here is the model. You can include related objects with the includes method from ActiveRecord. Because you want events in the end, just start the query from the Event model. Here's the simplest solution I can think of:

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

if you don't need the venue data, just use joins:

Event.joins(:venue).where(:venues => {:user_id => current_user.id})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top