2016-04-30 60 views
1

我學會了如何使用查詢與這個問題的關係。Ruby on Rails其中嵌套關係查詢

Ruby on Rails where query with relations

但是,我仍然無法正確使用這種嵌套的情況下做到這一點。 如何讓Summaries控制器索引工作?

模型

User 
    has_many :projects, dependent: :destroy 
    has_many :reasons, through: :projects 
    has_many :summaries, through: :projects, source: :reasons 
    has_many :entries, through: :projects 

Project 
    belongs_to :user 
    has_many :reasons 
    has_many :entries, through: :reasons 

Reasons 
    belongs_to :project 
    has_many :entries, dependent: :destroy 
    has_many :summaries, dependent: :destroy 

Summary 
    belongs_to :reason 

Entry 
    belongs_to :reason 

EntriesController

# GET /entries 
    def index 
    entries  = current_user.entries 
    updated_at = params[:updated_at] 

    # Filter with updated_at for reloading from mobile app 
    if updated_at.present? 

     # THIS WORKS!!!!!!!!!!!!! 
     entries = entries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i)) 

    # Get all non deleted objects when logging in from mobile app 
    else 
     entries = entries.where(deleted: false) 
    end 

    render json: entries 
    end 

SummariesController

# GET /summaries 
    def index 
    summaries = current_user.summaries 
    updated_at = params[:updated_at] 

    # Filter with updated_at for reloading from mobile app 
    if updated_at.present? 



     #THIS DOES NOT WORK, what can I do????? 
     summaries = summaries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i)) 



    # Get all non deleted objects when logging in from mobile app 
    else 
     summaries = summaries.where(deleted: false) 
    end 

    render json: summaries 
    end 

@Error登錄的iOS

錯誤:錯誤域= com.alamofire.error.seri alization.response Code = -1011「請求失敗:內部服務器錯誤(500)」UserInfo = {NSUnderlyingError = 0x1481b9030 {錯誤域= com.alamofire.error.serialization.response代碼= -1016「請求失敗:無法接受的內容類型: text/html的」

@Error登錄Heroku的

[1分[36mUser負荷(2.0ms)[0分[1mSELECT 「用戶」。* FROM 「用戶」 ORDER BY 「用戶」, 「ID」 ASC LIMIT 1 [0m 2016-04-30T07:48:18.909397 + 00:00 app [web.1]:在4ms內完成500次內部伺服器錯誤(ActiveRecord:2.0ms) 2016-04-30T07:48:18.910250 + 00: 00 app [web.1]:ActiveRecord :: ConfigurationError(在Reason中未找到名爲'reason'的關聯;也許你拼錯了嗎?):

+0

你能更具體地說明什麼不起作用嗎?你在'summaries = summaries.joins(:reason).where(「reasons.updated_at>?」,Time.at(updated_at.to_i))''上得到的錯誤是什麼? –

+0

我用錯誤日誌更新了我的問題,謝謝! –

回答

1

首先,你以非常偶然的方式引用reasonsUser has_many reasonsprojects,那麼爲什麼不去那條路?

current_user.joins(:reasons).where(reasons.updated_at > ?", updated_at) 

第二,更具體到你的錯誤:你的關係定義has_many :summaries, through: :projects, source: :reasons似乎因爲projects被打破沒有任何summaries

考慮在您的Project型號中添加has_many :summaries, through: :reasons,然後在User中使用has_many :summaries, through: :projects

+0

非常感謝!它像你說的那樣通過更新模型來工作! –