【问题标题】:rails app grab info from another table for each indexrails app 从另一个表中获取每个索引的信息
【发布时间】:2015-01-25 19:35:59
【问题描述】:

我是 Rails 新手,感谢您的帮助

我想当 rails 应用程序显示所有帖子时,使用 user_i tod 从另一个表(employer_info 表)中获取信息

作为一个例子,我对 show action/view 做了类似的事情。

后控制器

def index
    @posts = Post.all.order("created_at DESC")
end
def show
    @post = Post.find(params[:id])
    @employer_info = @post.user.employer_info
end

它使用post表中存储的user_id来查找对应的employer_info

对应型号

class EmployerInfo < ActiveRecord::Base
    belongs_to  :user
end
class Post < ActiveRecord::Base
    belongs_to  :user
end
class User < ActiveRecord::Base
  has_many  :posts
  has_one       :employer_info
end

对应视图

Show page
<%= @post.title %>
<%= @post.body %>
<%= @employer_info.name %>

Index Page
<% @posts.each do |p| %>
<%= link_to p.title, p %>
<% end %>

对于索引页面,我希望每个帖子列表也可以从 user_info 表中获取名称,类似于显示操作

有什么想法吗?

【问题讨论】:

    标签: sql ruby-on-rails ruby


    【解决方案1】:

    试试这个,我想它会有所帮助。

    <% @posts.each do |p| %>
      <%= link_to p.title, p %>
      <%= p.user.employer_info %>
    <% end %>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多