【发布时间】:2014-06-23 12:05:17
【问题描述】:
我目前有这样的设置:
公司.rb
has_many :applications
Application.rb
belongs_to :company
has_many :answers
并在公司创建应用程序时将 company_id 存储为 company_id。 公司可以在应用程序中创建问题。存储为 question_1、question_2 和 question_3
然后我有
Answers.rb
has_many :users
其中包含 answer_1、answer_2、answer_3 并存储回答者的 user_id。
我已经在 Answers 中设置了控制器,以便在
中查看应用程序answers#show
与路由:
match '/answers/:id', to: 'answers#show', via: 'get'
所以当我访问 /answers/5 时,我得到应用程序属于用户 ID 为 1 的公司,应用程序属于 ID 为 10 的应用程序。例如。 我通过显示在 answers/show.html.erb 中得到了这一点:
<%= @application.company_id %>
<%= @application.id %>
现在我在节目中创建了一个如下所示的表单:
<%= form_for @answer do |f| %>
<p>Question 1: <%= @application.question_1 %></p>
<%= f.text_area :answer_1 %><br/>
<p>Question 2: <%= @application.question_2 %></p>
<%= f.text_area :answer_2 %><br/>
<p>Question 3: <%= @application.question_3 %></p>
<%= f.text_area :answer_3 %>
<%= f.submit "Submit" %>
<% end %>
answers_controller.rb 看起来像这样:
class AnswersController < ApplicationController
before_action :authenticate_user!
def new
@answer = Answer.new
end
def show
@application = Application.find(params[:id])
@answer = Answer.new
end
def create
@answer = Answer.new(answer_params.merge(:user_id => current_user.id))
if @answer.save
redirect_to root_url
else
render 'new'
end
end
private
def answer_params
params.require(:answer).permit(:answer_1, :answer_2, :answer_3)
end
end
所以当我回答一个问题时,它会像这样将它存储在数据库中:
当我创建一个应用程序时,它会像这样将它存储在数据库中:
我现在想要的是答案与 application_id 相关联。我不确定如何进行双重合并,因为我已经从 current_user.id 中获取了 user_id。
最终目标是让公司能够查看用户以及他们对其应用程序的回答。
那么我该如何添加它,以便我可以保存这些答案所属的 current_user.id 和 application_id。我知道必须有一些简单的方法,因为我的路由已经显示了您正在回答的应用程序。但不确定如何将其添加到数据库(控制器)
【问题讨论】:
标签: mysql ruby-on-rails ruby ruby-on-rails-3