【发布时间】: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