简体   繁体   English

ruby on rails如何从视图访问左连接变量

[英]ruby on rails how to access left join variables from view

My Index Controller: 我的索引控制器:

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

How can i access the users.username from the view? 如何从视图访问users.username?

I tried 我试过了

<% @posts.each do |post| %>
    <%= post.username %>
<% end %>

but it doesn't seem to work since i get a blank message... 但这似乎不起作用,因为我收到一条空白消息...

EDIT: 编辑:

i had to use the following code in the LEFT JOIN: 我必须在LEFT JOIN中使用以下代码:

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

Try this .. 尝试这个 ..

@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 %>

我必须在LEFT JOIN中使用以下代码:

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

Your code is not MVC friendly. 您的代码不是MVC友好的。 This is how its better done in Rails. 这是在Rails中更好的方法。

1. Your models should do the queries: 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. Call the query in the controller 2.在控制器中调用查询

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

3. Then you could do, in your view 3.然后,您可以做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM