mysql - 通过加入的数据库显示用户全名

标签 mysql ruby-on-rails ruby ruby-on-rails-4

我被困住了。

我目前正在尝试打印数据库用户中的全名列。

我的数据库是这样连接的。

4 个型号。公司、应用程序、答案、用户。

公司创建了一个可由用户回答的应用程序。

company.rb

has_many :applications
has_many :answers, through: :applications

application.rb

belongs_to :company
has_many :answers

answer.rb

belongs_to :application
has_many :users

user.rb

has_many :answers

公司创建了一组问题,这些问题存储在应用程序中。用户可以查看这些问题并回答它们。答案存储在答案中。当他们回答时,我将他们的 user_id 存储在 answer.rb 中。

我想做的是向公司展示哪个用户回答了他们的问题。我已经能够打印出他们的 user_id,但不能打印出他们的 .fullname。

这就是我当前的设置:

<h1>People who've applied to your startup</h1>

<% @applications.all.each do |application| %>
 <% application.answers.each do |answer| %>

  <p>Your question1: <%= answer.application.question_1 %></p>
  <p>Their answer 1: <%= answer.answer_1 %></p>
 <p>Your question 2: <%= answer.application.question_2 %></p>
  <p>Their answer 3: <%= answer.answer_2 %></p>
  <p>Your question 3: <%= answer.application.question_3 %></p>
  <p>Their answer 3: <%= answer.answer_3 %></p>


  <i>Answered by user: <%= answer.user_id %></i>
  <hr>

这成功打印出了他们的 user_id。不过,我想更进一步,了解他们的全名。那么我该怎么做呢?他们的全名存储在 user.rb 模型中。

最佳答案

我认为更好的答案是:

class Answer < ActiveRecord::Base
  belongs_to :application
  belongs_to :user #here
  delegate :fullname, to: 'user', allow_nil: true, (optional) prefix: 'user'
end 

现在你可以做

<%=answer.fullname%> or if you add the optional part <%=answer.user_fullname%>

如果您选择这种方式,请阅读更多内容 delegate .

前缀不必称为“用户”

delegate :fullname, to: 'user', allow_nil: true, prefix: 'any_name'

<%= answer.any_name_fullname%>

关于mysql - 通过加入的数据库显示用户全名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24428665/

相关文章:

PHPExcel Reader 抛出异常

ruby-on-rails - Cookie 溢出与 Twitter 登录

ruby-on-rails - rails : Better way to create variables for views

ruby-on-rails - Ruby on Rails - 连接两个表将结果添加到 JSON

ruby - 我在 Sinatra 应用程序中收到 "Heroku push rejected, no Rails or Rack app detected"错误

ruby - resque-scheduler 在作业删除时失败

mysql - 使用 Group BY 按条件查询列计数

php - 表单未填写表格并返回空白页

mysql - SQL查询来自满足条件的两个表

ruby-on-rails - locale 显然存在时无效