stergosz
stergosz

Reputation: 5860

ruby on rails access associated table from view

I have a method in my Post model which gets the user posts

  def self.find_user_posts(user_id)
    where(:user_id => user_id).limit(15)
  end

then in view i have

<% Post.find_user_posts(@user.id).each do |p| %>
    <%= render_post(p) %>
<% end %>

which then call a partial called /posts/_post.html.erb

my problem is that i want to get each user picture from the users table since both tables share a foreign column called user_id

i also have in post model

belongs_to :user, :foreign_key => 'post_id'

and in user model

has_many :post, :foreign_key => 'post_id'

Upvotes: 0

Views: 247

Answers (1)

EnabrenTane
EnabrenTane

Reputation: 7466

You can simplify this.

in your view

<% @user.posts.limit(15).each do |post| %>
  <%= render_post(post) %>
<% end %>

This will let you delete

def self.find_user_posts(user_id)
    where(:user_id => user_id).limit(15)
end

Which should be a named_scope if needed.

Then in your _post partial you should be able to do something like

<%= image_tag(post.user.image_url) %>

to show each user's image it per post.

Upvotes: 1

Related Questions