我学会了如何使用来自这个问题的关系查询。
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
iOS上的@Error登录
错误:错误Domain = com.alamofire.error.serialization.response Code = -1011“请求失败:内部服务器错误(500)”UserInfo = {NSUnderlyingError = 0x1481b9030 {Error Domain = com.alamofire.error.serialization。响应代码= -1016“请求失败:不可接受的内容类型:text / html”
@错误登录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'的关联;也许你拼错了吗?):
答案 0 :(得分:1)
首先,您以非常随意的方式引用reasons
。 User
has_many 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: :projects
中使用User
。