0

我深深嵌套的資源下面的相關數據:如何從深度嵌套資源

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 

我想用檢索屬於特定用戶的所有eventsactiverecord

下面我試過,但這個似乎沒有被產生,我想其結果是事件數據:

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 
+0

顯示你的事件模型的代碼,與事件表的列名 – beck03076

+0

沿@ beck03076我剛剛更新了事件模型 –

+0

所以事件屬於Venue,Venue belongs_to用戶。用戶has_many場地和場地has_many事件。您的輸入是current_user id。所以,你想,所有的事件belongs_to current_user的場地? – beck03076

回答

0

的路由是不是從數據庫中的記錄檢索重要。唯一重要的是模型。您可以使用the includes method from ActiveRecord包含相關對象。因爲最後需要事件,所以只需從Event模型啓動查詢即可。這是我能想到的最簡單的辦法:

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

,如果你不需要場地數據,只需使用joins

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

我得到這個錯誤'沒有路線匹配{:控制器=>「事件」,:行動=>「顯示」}缺少必需的鍵:[:id]' –

+0

對不起,更新了我的答案。我認爲這應該現在沒有任何修改。 –

+0

我得到'沒有路由匹配{:controller =>「events」,:action =>「show」}缺少必需的鍵:[:id]' –