我正在尝试使用带有关系的查询和updated_at比较。
当我使用updated_at参数发送此查询时,我只想获取由updated_at日期过滤的最新原因,但是它会过滤项目的updated_at,而不是原因updated_at。
如何解决此问题以使用updated_at过滤器获取原因数据?
@Getting reason with updated_at filter
https://server.com/api/v1/entries?updated_at=2016-05-02T01:12:57.204Z
@Model
User
has_many :projects
has_many :reasons, through: :projects
Project
belongs_to :user
has_many :reasons
Reasons
belongs_to :project
@Reasons Controllers
# GET /reasons
def index
reasons = current_user.reasons
updated_at = params[:updated_at]
# Filter with updated_at for reloading from mobile app
if updated_at.present?
# This is my first try, but it shows error because of relations
# reasons = reasons.where("updated_at > ?", DateTime.parse(updated_at))
# This shows reasons data, but it only compares updated_at in Project data, not reasons data...
reasons = reasons.joins(:project).where("projects.updated_at > ?", DateTime.parse(updated_at))
# Get all non deleted objects when logging in from mobile app
else
reasons = reasons.where(deleted: false)
end
render json: reasons
end
答案 0 :(得分:2)
您提取projects.updated_at
,但如果我理解正确,您需要提取reasons.updated_at
reasons = reasons.joins(:project).where("reasons.updated_at > ?", DateTime.parse(updated_at))
为我生产输出
GET http://localhost:3000/reasons/index?updated_at=2016-05-04T06:43:19.280Z
[
{
"id": 2,
"name": "R2",
"project_id": 3,
"created_at": "2016-05-04T06:43:19.280Z",
"updated_at": "2016-05-04T06:43:19.280Z",
"deleted": false
},
{
"id": 3,
"name": "R3",
"project_id": 3,
"created_at": "2016-05-04T06:43:25.895Z",
"updated_at": "2016-05-04T06:43:25.895Z",
"deleted": false
}
]
没有任何过滤器
GET http://localhost:3000/reasons/index
[
{
"id": 1,
"name": "R1",
"project_id": 3,
"created_at": "2016-05-04T06:43:11.044Z",
"updated_at": "2016-05-04T06:43:11.044Z",
"deleted": false
},
{
"id": 2,
"name": "R2",
"project_id": 3,
"created_at": "2016-05-04T06:43:19.280Z",
"updated_at": "2016-05-04T06:43:19.280Z",
"deleted": false
},
{
"id": 3,
"name": "R3",
"project_id": 3,
"created_at": "2016-05-04T06:43:25.895Z",
"updated_at": "2016-05-04T06:43:25.895Z",
"deleted": false
}
]
答案 1 :(得分:0)
它只是改为reason.updated_at,谢谢!
reasons = reasons.joins(:project).where("reasons.updated_at > ?", DateTime.parse(updated_at))