1

我目前正在尝试创建一个调查,该调查将使用存储在表格中的问题。我已经从 rails casts 中阅读了嵌套模型形式的第 1 部分,但是由于调查中没有显示问题,所以我没有得到任何结果。

我有三个表格,一个表格包含问题的文本,另一个表格记录谁进入了调查,第三个表格记录了用户对问题的回答。

变量表:名称:varchar id:整数

报表表 员工姓名:varchar 日期:日期 id:整数

report_variable 表 question_id report_id 答案

我为报告/新修改的代码:

 # GET /reports/new
 # GET /reports/new.json
 def new
   @report = Report.new
   #variable = @report.variable.build #dont know what to do here, gives an error with report_id
   respond_to do |format|
     format.html # new.html.erb
     format.json { render json: @report }
   end
 end

修改报告/_form.html.erb

   <div >
     <%= f.fields_for :variable do |builder| %>
       <%= render variable_fields, :f => builder %>
     <% end %>
   </div>

创建报告/_variable_fields.html.erb

   <p>
      <%= f.label :name %>
      <%= f.text_field :name, :class => 'text_field' %>
   <p>

report_variable 的模型

class ReportVariable < ActiveRecord::Base
  attr_accessible :report_id, :value, :variable_id
  has_and_belongs to many :reports
  has_and_belongs to many :variables
end

报告模型

class Report < ActiveRecord::Base
  attr_accessible :employeeName
  has_many :report_variable
  has_many :variable

  accepts_nested_attributes_for :report_variable
  accepts_nested_attributes_for :variable
end

对不起,如果这是一个简单的问题,我对 Rails 很陌生。

4

1 回答 1

2

Welcome to Rails!

I think the simple answer is the fields aren't showing up because there aren't any nested records. You can probably get around that by uncommenting the variable line as you have it:

def new
  @report = Report.new
  @report.variables.build #this line creates 1 new empty variable, unsaved.
  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @report }
  end
end

If you want more than one variable, call something like:

3.times { @report.variables.build }

That way the @report object you're placing in the form helper will have three variables on it. This should get you moving again, the harder thing is going to be adding ajax addition / removal of variables, but if you know how many there are in advance you don't have to deal with that.

Good luck!

于 2012-11-08T00:59:32.953 回答