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