我的索引控制器:Ruby on Rails的如何訪問從左側視圖
class IndexController < ApplicationController
def index
@posts = Post.find(:all, :limit => 10,
:joins => "LEFT JOIN `users` ON users.user_id = posts.user_id",
:select => "posts.*, users.username",
:order => "posts.created_at DESC")
end
end
如何從視圖訪問users.username?
我試圖
<% @posts.each do |post| %>
<%= post.username %>
<% end %>
,但它似乎並沒有工作,因爲我得到了一個空白消息...
編輯:
我不得不使用下面的代碼LEFT JOIN:
:joins => "LEFT JOIN `users` ON posts.user_id = users.id",
會不會'@ post.user.username'工作? – x1a4
@ x1a4我得到了'undefined method'user'for#<發佈:0x4281918>' – fxuser
您是否在帖子和用戶之間有關聯?看起來您已經擁有數據庫設置,如果是這種情況,那麼您的Post模型會添加1行更新以添加關聯。 – x1a4