Rails / PostgreSQL - 查询更新所有添加1天的日期

时间:2018-02-27 15:07:59

标签: sql ruby-on-rails postgresql activerecord

我想执行update_all查询来更新datetime列,将所有行的此列的当前值添加1天。

我可以使用.each和.update实现这一点,但在单个查询中执行会更有效。

是否可以使用Rails和PostgreSQL实现这一目标?

2 个答案:

答案 0 :(得分:4)

<a :href="rows[0]['href']">Go Back</a>

OR

UPDATE table SET date_field = date_field + 1;

答案 1 :(得分:1)

Rails更新所有记录的方式

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        if (response instanceof HttpServletResponse) {
            addCorsHeader(response);
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                filterChain.doFilter(req, res);
            }
        }
    }

    private void addCorsHeader(HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "http://localhost:4200"); // Update with yours
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
        response.addHeader("Access-Control-Max-Age", "1728000");
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

此更新查询可以通过rails console运行。

注意:update_all方法不会触发Active Record回调或验证,也不会更改updated_at时间戳。