简体   繁体   中英

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?

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:

: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. This is how its better done in Rails.

1. Your models should do the queries:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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