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

Mysql 通过加入的数据库显示用户全名,mysql,ruby-on-rails,ruby,ruby-on-rails-4,Mysql,Ruby On Rails,Ruby,Ruby On Rails 4,我被卡住了 我目前正在尝试打印数据库用户中的全名列 #answer.rb Class Answer < ActiveRecord::Base belongs_to :application belongs_to :user #here end 我有这样连接的数据库 4种型号。公司、应用程序、答案、用户 该公司创建了一个应用程序,用户可以回答 公司。rb has_many :applications has_many :answers, through: :applications

我被卡住了

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

#answer.rb
Class Answer < ActiveRecord::Base

belongs_to :application
belongs_to :user #here

end
我有这样连接的数据库

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

该公司创建了一个应用程序,用户可以回答

公司。rb

has_many :applications
has_many :answers, through: :applications
belongs_to :application
has_many :users
has_many :answers
应用程序.rb

belongs_to :company
has_many :answers
答案是rb

has_many :applications
has_many :answers, through: :applications
belongs_to :application
has_many :users
has_many :answers
user.rb

has_many :applications
has_many :answers, through: :applications
belongs_to :application
has_many :users
has_many :answers
公司创建了一组问题,这些问题存储在应用程序中。用户可以查看并回答这些问题。答案存储在answer中。当他们回答时,我将他们的用户id存储在answer.rb中

我想做的是向公司展示哪个用户回答了他们的问题。我可以打印出他们的用户名,但不能打印出他们的.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>
向您的初创公司申请的人
你的问题1:

他们的答案1:

你的问题2:

他们的答复3:

你的问题3:

他们的答复3:

用户回答:

这成功地打印出了他们的用户名。但是我想更深入一步,访问他们的全名。那我该怎么做呢?他们的全名存储在user.rb模型中。

首先,你的
用户
答案之间的
关系似乎是错误的。你应该拥有
属于
答案
中的
用户
模型中的
没有很多:用户

#answer.rb
Class Answer < ActiveRecord::Base

belongs_to :application
belongs_to :user #here

end
#answer.rb
类答案
第二,通过这样做,你可以这样做

<%= answer.user.fullname %>

要获取
答案的相关
用户全名

#answer.rb
Class Answer < ActiveRecord::Base

belongs_to :application
belongs_to :user #here

end

此外,您还应该查看这些以了解更多信息。

我认为更好的答案是:

class Answer < ActiveRecord::Base
  belongs_to :application
  belongs_to :user #here
  delegate :fullname, to: 'user', allow_nil: true, (optional) prefix: 'user'
end 
class-Answer
现在你可以做了

<%=answer.fullname%> or if you add the optional part <%=answer.user_fullname%>
或如果您添加可选零件
如果你喜欢这种方式,请阅读更多

前缀不必称为“用户”

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

<%= answer.any_name_fullname%>
delegate:fullname,to:'user',allow\u nil:true,前缀:'any\u name'

试着这样给它
@Pavan我得到了一个未定义的方法“user”。你的关联似乎是错误的。你应该在
答案中有
属于:user
。rb
不是
有很多:users
。更改它,然后再试一次。@Pavan它工作:)非常感谢我把它作为答案发布了:)我也更喜欢委托。如果要使用要委派的属性作为前缀,可以说
prefix:true
delegate:fullname,to::user,allow_nil:true,prefix:true
将产生与上述相同的结果。