Querying multiple linked classes in Rails -


i want query multiple tables. example in posts table there user_id linked users id. while showing every post, want display picture of user. approach this, there problem. @user.picture method undefined.

<% @programs.each |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 %> 

program controller:

class programcontroller < applicationcontroller def index   @programs = program.all end 

user model:

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 

program model:

class program < activerecord::base   attr_accessible :details, :title, :user_id   belongs_to :user   has_many :programdetails end 

try instead, in controller:

@programs = program.includes(:user) # return programs , related users in                                     # 2 database queries rather n+1 queries 

then in view:

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

also, can use image_tag instead.

finally, can change post title link to:

<%= link_to post.title.upcase, all_posts_path, :class => "posttitle" %> 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -