1

現在、テーブルに保存されている質問を使用する調査を作成しようとしています。Railsキャストからネストされたモデルフォームパート1を読みましたが、質問が調査に表示されていないため、どこにも到達していません。

私には3つのテーブルがあり、1つのテーブルには質問のテキストがあり、もう1つのテーブルには調査に参加した人の記録があり、3番目のテーブルにはユーザーからの質問に対する回答があります。

変数テーブル:名前:varchar id:整数

レポートテーブルの 従業員名:varchar日付:日付ID:整数

report_variableテーブル question_idreport_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

変更されたreport/_form.html.erb

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

report/_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

Railsへようこそ!

簡単な答えは、ネストされたレコードがないためにフィールドが表示されないことだと思います。あなたがそれを持っているようにあなたはおそらくそのvariable行のコメントを外すことによってそれを回避することができます:

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

複数の変数が必要な場合は、次のように呼び出します。

3.times { @report.variables.build }

そう@reportすれば、フォームヘルパーに配置するオブジェクトには、3つの変数が含まれます。これで再び動き出すはずです。難しいのは、変数のajaxの追加/削除を追加することですが、事前にいくつあるかがわかっている場合は、それに対処する必要はありません。

幸運を!

于 2012-11-08T00:59:32.953 に答える