0

複数のテーブルをクエリしたい。たとえば、投稿テーブルには、ユーザー ID にリンクされた user_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

すでに定義したリレーションを使用して、これを行うためのはるかに簡単な方法があります。

プログラムコントローラー

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 に答える
1

これを変更してみてください:@user = User.where("id = post.user_id")

これに:@user = User.where(id: post.user_id).first

またはさらに良い:@user = post.userキッドレールによって提案されたように

于 2013-05-14T14:31:22.920 に答える
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 に答える