Non Umemoto Non Umemoto - 7 months ago 23
Ruby Question

Ruby on Rails where query with relations and updated_at compare

I am trying to use where query with relationships and updated_at compare.

When I send this query with updated_at params, I want to fetch only the latest reasons filtered by updated_at date, but it filters with project's updated_at, not by reasons updated_at.

How can I fix this to get reasons data with updated_at filter?

@Getting reasons 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

Answer

You fetching projects.updated_at, but if I understood you right you need to fetch reasons.updated_at

reasons = reasons.joins(:project).where("reasons.updated_at > ?", DateTime.parse(updated_at))

produses that output for me

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
    }
]

And without any filter

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
    }
]