0

私はrailscastsで見ていて、自分の手で例を書き込もうとしました。しかし、次のステップで問題が発生しました。フォームを作成します。

調査と質問の間の関連付けを作成する必要があります。しかし、この関連付けは私の Rails アプリケーションでは確立できないため、フォームに質問は表示されません。

ここにコードがあります

調査モデル:

class Survey < ActiveRecord::Base
  attr_accessible :name, :questions
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions

end

質問モデル:

class Question < ActiveRecord::Base
  attr_accessible :context, :survey_id
  belongs_to :survey
end

Surveys_Controller メソッド:

  # GET /surveys/new
  # GET /surveys/new.json
  def new
    @survey = Survey.new
    3.times {@survey.questions.build}


    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @survey }
    end
  end

_form.html.erb の質問部分

  <% f.fields_for :questions do |builder|%>
    <%= builder.label :context, "Question" %><br />
    <%= builder.text_area :context, :rows => 3 %>
  <% end %>

これがコンソールでのテストから得たものです

irb(main):010:0> @survey = Survey.new
=> #<Survey id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):011:0> 3.times {@survey.questions.build}
=> 3
irb(main):012:0> @survey.questions
=> [#<Question id: nil, survey_id: nil, context: nil, created_at: nil, updated_a
t: nil>, #<Question id: nil, survey_id: nil, context: nil, created_at: nil, upda
ted_at: nil>, #<Question id: nil, survey_id: nil, context: nil, created_at: nil,
 updated_at: nil>]
4

3 に答える 3

1

モデル用の新しいオブジェクトがあります。空のオブジェクトに対して 3 つの質問を作成します。質問は空でなければなりません。保存も定義もされていません。

于 2012-09-03T11:47:20.210 に答える
1

私があなたの質問を正しく理解していれば、フォームに質問が表示されていません。フォームには、1 つの質問に対して 1 つのフォームが必要です。あなたのフォームでquestions.eachをやっていますか?

次のようなものが必要です:

<% survey.questions.each do |question| %>
      <%= fields_for question do |builder| %>
于 2012-09-03T11:49:49.580 に答える
0

ハハ、私は愚かです。ばかげた質問です。協会は問いません。

で入力ミスをしました

<% f.fields_for :questions do |builder|%>

Rubyコードとして処理するだけでなく、HTMLドキュメントに挿入するテキストを返す必要があります

そのはず<%= f.fields_for :questions do |builder|%>

しかし、あなたのすべての答えに感謝します:)

于 2012-09-03T12:54:14.453 に答える