【发布时间】:2023-04-05 13:53:01
【问题描述】:
我从这个问题中学会了如何使用 where 查询与关系。
Ruby on Rails where query with relations
但是,我仍然无法正确处理这个嵌套案例。 如何使摘要控制器索引工作?
型号
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 上的错误日志
错误:错误域=com.alamofire.error.serialization.response Code=-1011 “请求失败:内部服务器错误 (500)”UserInfo={NSUnderlyingError=0x1481b9030 {错误域=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]:在 4 毫秒内完成 500 个内部服务器错误(ActiveRecord:2.0 毫秒) 2016-04-30T07:48:18.910250+00:00 app[web.1]: ActiveRecord::ConfigurationError(在 Reason 上找不到名为“reason”的关联;也许你拼错了?):
【问题讨论】:
-
您能否更具体地说明什么不起作用?您在
summaries = summaries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i))上遇到什么错误? -
我用错误日志更新了我的问题,谢谢!
标签: sql ruby-on-rails ruby activerecord