在Rails中查询多个链接的类

时间:2013-05-14 14:22:21

标签: ruby-on-rails

我想查询多个表。例如,在posts表中有一个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 个答案:

答案 0 :(得分:1)

@user = post.user。 Rails关联将自行回馈相关用户。

并在语法上修正上述@user = User.find(post.user_id)

答案 1 :(得分:1)

尝试更改此内容:@user = User.where("id = post.user_id")

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

或甚至更好:{child}的建议

@user = post.user

答案 2 :(得分: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" %>

答案 3 :(得分: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 %>