0

コースが選択されたときに、アクションを使用してコースのすべてのトピックを表示しました。number_questionここで、仮想属性を使用して、使用するトピックごとにフォームにフィールドを表示し、数値を入力できるようにしたいと考えています。私のモデル:

class GeneralExam < ActiveRecord::Base
  attr_accessible :course_id, :description
  attr_accessor :numbe_question
end

これは私のフォームです:

<%= simple_form_for @general_exam, defaults: { error: false } do |f| %>
            <fieldset>
                <legend>General Exam information</legend>
                <%= render 'shared/error_messages', object: f.object %>
                    <%= f.association :course, collection: current_user.courses, prompt: "Choose Course for exam"  %>
                    <%= f.input :name %>
                    <%= f.input :description, input_html: { rows: 2, class: 'span6' } %>
            </fieldset>

            <fieldset>
                <legend>Choose number question for topics</legend>
                <div id="list_topics">
                </div>
            </fieldset>
            <%= f.submit class: "new_resource" %>
<% end %>

これは私の行動です:

  def update_topics
    @course = Course.find(params[:course_id])
    @topics = @course.topics
  end

じぶんのupdate_topics.js.erb

$('#list_topics').html("<%= j (render('general_exams/list_topics')) %>")

私の_list_topics.html.erb部分:

<% @topics.each do |topic| %>
    <h5><%= topic.name %></h3>
    <%# f.input :number_question, input_html: { name: "number_question[#{topic.id}]" } %>
<% end %>

しかし、入力フィールドを表示したい場合はfオブジェクトが必要ですが、レンダリングするとオブジェクトが_list_topicsありませんでした。fフォームのオブジェクトをパーシャルに渡す方法を知りたい_list_topicsですか?

または、jquery を使用してフォームの要素の後に入力フィールドを追加する方法を誰かが教えてくれますh5。どうもありがとうございました。

4

1 に答える 1

3

問題を解決するには、いくつかの異なるアプローチがあると思います。そのうちの 2 つ (私:

1) number_question データを別のコントローラー アクションに投稿する別のフォームを定義できます。2) ユーザーがフィールド値の更新を終了したら、jquery の変更コールバックを使用して number_question を送信します。

最初のオプションの方が優れており、コーディングが簡単だと思います。次のような結果になります。

<%= simple_form_for @general_exam, defaults: { error: false } do |f| %>
    <fieldset>
        <legend>General Exam information</legend>
        <%= render 'shared/error_messages', object: f.object %>
            <%= f.association :course, collection: current_user.courses, prompt: "Choose Course for exam"  %>
            <%= f.input :name %>
            <%= f.input :description, input_html: { rows: 2, class: 'span6' } %>
    </fieldset>
    <%= f.submit class: "new_resource" %>
<% end %>

次に、同じテンプレートに別のフォームを作成します (トピック番号を送信するため):

<%= simple_form_for @general_exam, url: whatever_is_your_new_topics_number_path, defaults: { error: false } do |f| %>
    <fieldset>
        <div id="list_topics">
        </div>
    </fieldset>
<% end %>

引き続き JS パーシャルで応答し、トピック データに応じて div のコンテンツを置き換えます。

于 2012-11-21T19:09:41.847 に答える