[英]Select multiple values from associated model rails
假設我有這個關聯
User have_many posts
Post belongs_to user
User Post
----------------
id id
name title
user_id
如何只列出包含標題/標題的帖子標題和用戶名?
(帖子列表[標題-用戶名])
@posts = Post.includes(:user).select('........')
不要提供這個
@posts = Post.all.each {|p| p.user.username}
__________________UP_____________________
它適用於連接2個表。
如果我想將其用於更復雜的示例怎么辦?
看看我的上一個問題優化sql查詢rails
@Humza的答案部分起作用。 可能是這樣的
@posts = Post.joins(:user, :category).paginate(:page => params[:page]).order("created_at DESC")
但不會顯示沒有類別的帖子
我還需要顯示gravatar,但是我想我可以只將user.email用作usr_email並使用gravatar_for(post.usr_email),但是我必須為此自定義gravatar助手。
posts_controller.rb
def index
@posts = Post.includes(:user).includes(:comments).paginate(:page => params[:page]).order("created_at DESC")
end
index.html.erb
<%= render @posts %>
_post.html.erb
<%= gravatar_for post.user, size:20 %>
<%= link_to "#{post.title}", post_path(post) %>
<%= time_ago_in_words(post.created_at) %>
<%= post.comments.count %>
<%= post.category.name if post.category %>
看一下拔毛 。
Post.joins(:user).pluck(:title, :name)
請注意,在這種情況下它可以工作,因為name
列沒有歧義,您可能希望顯式指定表( pluck(:title, "users.name")
)。
includes
在急切加載的情況下。 在這種情況下,您需要joins
。
posts = Post.joins(:user).select("posts.title AS title, users.name AS username")
您可以通過以下方式訪問值:
post = posts.first
post.title # will give the title of the post
post.username # will give the name of the user that this post belongs to
如果你能pluck
多列,那么下面可能對你更有用。
posts = Post.joins(:user).pluck("posts.title", "users.name")
結果將是一個2D數組,每個元素都是[post_title, post_username]
形式的數組
您可以在范圍上調用數組方法,以便:
Post.includes(:user).map { |p| [p.title, p.user.name] }
將獲得包含用戶的帖子,並將每個帖子映射到帖子標題和用戶名的元組。
這可能無法完全回答您的問題,因為我認為您可能希望將查詢結果限制為僅必填字段,在這種情況下,我認為您可以將.select('title', 'users.name')
到查詢。 (目前無法測試)
Post.joins(:user, :category)
但不會顯示沒有類別的帖子
這是因為joins
使用INNER JOIN
將表joins
在一起。 如果您想要從Post
獲得所有內容,即使該特定記錄在另一個表中沒有對應的記錄,則需要使用LEFT JOIN
。 不幸的是, ActiveRecord
沒有生成它的好方法,您將需要手動進行:
Post.joins("LEFT OUTER JOIN categories ON categories.post_id = posts.id")...
有關更多信息,請參見SQL連接的直觀說明 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.