简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM