Ruby on Rails,其中查询具有嵌套关系

我学会了如何使用来自这个问题的关系查询。

Ruby on Rails在哪里查询关系

但是,我仍然无法使用这种嵌套案例。 如何使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 

在iOS上@Error登录

错误:错误Domain = com.alamofire.error.serialization.response Code = -1011“请求失败:内部服务器错误(500)”UserInfo = {NSUnderlyingError = 0x1481b9030 {Error Domain = com.alamofire.error.serialization.response Code = -1016“请求失败:不可接受的内容类型:text / html”

@Error登录Heroku

[1m [36mUser Load(2.0ms)[0m [1mSELECT“users”。* FROM“users”ORDER BY“users”。“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上找到;也许你拼错了吗?):

首先,你以非常随意的方式引用reasonsUser reasons通过projects ,所以为什么不去那条路?

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

其次,更具体的是你的错误:你的关系定义has_many :summaries, through: :projects, source: :reasons似乎被打破,因为projects没有任何summaries

考虑添加一个has_many :summaries, through: :reasons对你的Project模型的has_many :summaries, through: :reasons ,然后使用has_many :summaries, through: :projects in User