Nested Form complex has_many :through
我有一个复杂的has_many通过关系,用户可以在其中通过应用程序申请工作。
在创建每个作业时,管理员会选择某些问题。在Applications#new期间,当用户正在申请新工作时,我也希望用户回答问题才能申请。
为此,我按如下方式设置模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Job has many users through application has many questions Users has_many jobs through application Application belongs_to :user belongs_to :job has_many :answers Question belongs_to :job has_one :answer Answer belongs_to :application belongs_to :question |
我现在有一个应用程序控制器。
在这里我被困住了。如何使用户能够在Applications#new视图上回答问题?
这是到目前为止的样子->
应用程序控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class ApplicationsController < ApplicationController def new @application = Application.new() if params[:job_id] # Applications will only be built by clicking on a specific job, which transfers the id of that job @application.job_id = params[:job_id] @application.user_id = current_user.id else redirect_to root_url, :notice =>"Something went wrong. Please contact us and mention this" end @job = Job.find(@application.job_id) @user = current_user end end |
控制器实质上是对其进行设置的,以便当用户单击"提交"时,应用程序将具有用户ID和作业ID,从而有效地建立了连接。
Applications#new视图
1 2 3 4 5 6 7 8 | <%= form @application do |f| %> <%= render 'shared/error_messages', object: f.object %> <% @job.questions.each do |question| %> <h4><%= question.content %></h4> #What do I do here to allow the user to answer the question? <% end %> <%= f.submit"Submit the application", class:"button" %> <% end %> |
应用程序模型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # == Schema Information # # Table name: applications # # id :integer not null, primary key # user_id :integer # job_id :integer # created_at :datetime # updated_at :datetime # class Application < ActiveRecord::Base belongs_to :job belongs_to :user validates :job_id, presence: true validates :user_id, presence: true has_many :answers accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true end |
棘手的问题....
这可能不起作用(特别是关联