0

特定のパラメータに基づいて新しいオブジェクトを作成したい。

私のnew.html.hamlで

%table
   %thead
      %tr
        %td
          = f.label: type
         %td
           = select_tag :question_type, options_for_select
    %tbody#content

javascript:

$('#question_type').change(function(){
     $.ajax({
        data: { question_type: $(this).val() },
        url: window.location.href,
        dataType: 'script'
     });
  });

私のnew.js.hamlで

$('#content').html("#{escape_javascript(render(:partial => "question_form"))}");

_question_form.html.haml

= form_for @question, :url => {:action => "create"} do |f|
  %tr
    %td{:style => 'text-align:right;'}
      = f.label :name
    %td
      = f.text_field :name
  %tr
    %td
    %td
      = f.button :Submit, :value => 'Create'

私のコントローラーで

def new
   @question = Question.new

   respond_to do |format|
     format.html
     format.js
   end
  end

  def create
   @question.save

   respond_to do |format|
     format.html (redirect_to questions_path)
     format.js
   end
  end

すべて正常に動作していますが、質問名を入力してもフォームを送信できません。このフォームを送信するにはどうすればよいですか?

4

1 に答える 1

1

問題はHTML構造にあります。フォームをテーブルの外に置く必要があります。

= form_for @question do |f|
  %table

これにより、作成アクションで無視できる質問タイプが送信されることに注意してください。

アップデート:

# new.html.haml
#form-content= render 'question_form'

# _question_form.html.haml
= form_for @question, :url => {:action => "create"} do |f|
  %table
    %thead
      %tr
        %td= f.label: type
        %td= select_tag :question_type, options_for_select
    %tbody
      - if params[:question_type].present?
        %tr
          %td{:style => 'text-align:right;'}= f.label :name
          %td= f.text_field :name
        %tr
          %td
          %td= f.button :Submit, :value => 'Create'

# new.js.haml
$('#form-content').html("#{escape_javascript render("question_form")}");
于 2013-02-10T02:12:32.030 に答える