0

我的索引控制器:

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",
4

3 回答 3

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 %>
于 2012-06-29T08:38:51.127 回答
0

我不得不在 LEFT JOIN 中使用以下代码:

:joins => "LEFT JOIN `users` ON posts.user_id = users.id",
于 2012-06-29T08:43:17.430 回答
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 %>
于 2012-06-29T10:12:33.423 回答