2012-06-29 30 views
0
加入變量

我的索引控制器: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", 
+0

會不會'@ post.user.username'工作? – x1a4

+0

@ x1a4我得到了'undefined method'user'for#<發佈:0x4281918>' – fxuser

+0

您是否在帖子和用戶之間有關聯?看起來您已經擁有數據庫設置,如果是這種情況,那麼您的Post模型會添加1行更新以添加關聯。 – x1a4

回答

0

我只好用左下面的代碼JOIN:

:joins => "LEFT JOIN `users` ON posts.user_id = users.id", 
0

試試這個..

@posts = Post.find(:all, :limit => 10, 
          :joins => "LEFT JOIN `users` ON users.user_id = posts.user_id", 
          :select => "posts.*, users.username as user_name", 
          :order => "posts.created_at DESC") 


<% @posts.each do |post| %> 
    <%= post.user_name %> 
<% end %> 
+0

user_name給出了一個空白的消息,而不是正確的用戶名......怪異的 – fxuser

0

你的代碼不MVC友好。這是如何更好地在Rails中完成的。

1.你的模型應該做的疑問:

class User < ActiveRecord::Base 
    has_many :posts 
end 

class Post < ActiveRecord::Base 
    belongs_to :user 
    scope :last_10, order("created_at desc").limit(10) #or "id desc" which is quicker 
end 

2.呼叫控制器

class IndexController < ApplicationController 
    def index 
    @posts = User.find_by_username(the_username).posts.last_10 
    end 
end 

3.然後,你可以做查詢,在您的視圖

<% @posts.each do |p| %> 
    <%= post.user.username %> 
<% end %> 
+0

我添加了視圖部分。如果你想強制使用'joins'或者從用戶模型中進行帖子查詢,還有其他方法可以做到這一點。最好不要在控制器中使用查詢。控制器的工作是獲取請求,調用模型,然後用結果呈現正確的視圖。 –