1
我有我的控制器轨协会相同的列名
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
两者的关系有created_at
如何打印两个日期为registered date
和posted date
我有我的控制器轨协会相同的列名
@post = Post.joins(:customer).select("customers.*,posts.*").find params[:id]
两者的关系有created_at
如何打印两个日期为registered date
和posted date
您不必手动选择每个中的所有列表:
# this is fine
@post = Post.joins(:customer).find(params[:id])
# this is better (will not raise a RecordNotFound if no record found)
@post = Post.joins(:customer).where(id: params[:id]).first
在您看来,您可以访问这样的属性:
Post was created at: <%= @post.created_at %>
Customer registered at: <%= @post.customer.created_at %>
此代码依赖于列created_at
是邮政创建日期/客户注册的日期。这有时可能是错误的,如果你导入一个现有客户列表,例如
所以我必须添加列作为registered_at和posting_at的关系。我不能使用现有的created_at权利? – overflow
是的,你可以使用它们,但不建议。我会更新我的答案 – MrYoshiji
不,“@ post”是Post对象在数据库中保存的。 '@ post.customer'将返回与Post相关的Customer对象,'@ post.customer.username'将会显示它的用户名;} – MrYoshiji