2016-04-30 59 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

非常感谢!它像你说的那样通过更新模型来工作! –