简体   繁体   English

Ruby on Rails从视图访问关联表

[英]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 然后调用部分名为/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 我的问题是我想从用户表中获取每个用户图片,因为两个表共享一个名为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. 如果需要,应为named_scope。

Then in your _post partial you should be able to do something like 然后在_post部分中,您应该可以执行以下操作

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

to show each user's image it per post. 在每个帖子上显示每个用户的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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