0

我想查询多个表。例如,在帖子表中,有一个 user_id 链接到用户 ID。在显示每个帖子的同时,我还想显示用户的图片。我的方法是这样的,但是有一个问题。@user.picture方法未定义。

<% @programs.each do |post| %>
<%= @user = User.where("id = post.user_id") %>
<li class="one-third column">                         
<div class="wrapper">
<div class="postThumb"><img src="<%= @user.picture %>" /></div>
  <div class="postDetails">
    <%= link_to "#{ post.title.upcase! }".html_safe, all_posts_path, :class => "postTitle" %>
    <p><%= truncate post.details, :length => 90 %></p>
  </div> 
</div>
</li>
<% end %>

程序控制器:

class ProgramController < ApplicationController
def index
  @programs = Program.all
end

用户型号:

class User < ActiveRecord::Base

  attr_accessible :password, :username, :oauth_token, :provider, :uid, :oauth_expires_at, :picture, :email, :name, :location, :gender, :updated_at, :is_admin
  has_many :posts   
  has_one :program
  has_many :programdetails, :through => :program
end

程序模型:

class Program < ActiveRecord::Base
  attr_accessible :details, :title, :user_id
  belongs_to :user
  has_many :programdetails
end
4

4 回答 4

1

试试这个,在控制器中:

@programs = Program.includes(:user) # this will return all programs and related users in
                                    # 2 database queries rather than N+1 queries

然后在视图中:

<div class="postThumb"><img src="<%= post.user.picture %>" /></div>

此外,您可以改用image_tag

最后,您可以将帖子标题链接更改为:

<%= link_to post.title.upcase, all_posts_path, :class => "postTitle" %>
于 2013-05-14T14:34:23.813 回答
1

@user = post.user. Rails 关联会自行返回关联的用户。

并在语法上更正上述内容,@user = User.find(post.user_id)

于 2013-05-14T14:30:46.233 回答
1

尝试改变这个:@user = User.where("id = post.user_id")

进入这个:@user = User.where(id: post.user_id).first

甚至更好:@user = post.user正如 Kiddorails 所建议的那样

于 2013-05-14T14:31:22.920 回答
1

使用您已经定义的关系有一种更简单的方法来执行此操作:

程序控制器

def index
  @programs = Program.
    includes(:user). # eager load user relation to avoid n+1
    all
end

看法

<% @programs.each do |post| %>
  <li class="one-third column">                         
    <div class="wrapper">
      <div class="postThumb"><img src="<%= post.user.picture %>" /></div>
        <div class="postDetails">
          <%= link_to "#{ post.title.upcase! }".html_safe, all_posts_path, :class => "postTitle" %>
          <p><%= truncate post.details, :length => 90 %></p>
      </div> 
    </div>
  </li>
<% end %>
于 2013-05-14T14:37:04.210 回答