如何在Rails中预先填充动态添加的表单输入

时间:2015-07-26 19:03:47

标签: javascript jquery html ruby-on-rails forms

我有edit.html.erb@profile个实例。通常,当我加载表单时,表单内的输入会预先填充实例的相应属性。

e.g。 <%= f.text_field :name %>会从@profile.name预先填充其值。

我想在运行时使用jQuery添加其他字段,允许用户使用额外的动态添加输入来输入其他数据。

即。 @profile.subjects是包含主题及其描述的哈希(例如,它可以是{"math" => "I teach calculus", "science" => "I have a physics degree"}

我从@profile.subjects检索主题列表,并使用jQuery中的textareaappend()个元素插入到每个主题的表单中。

因此,如果@profile.subjects包含“math”和“science”,我将在jQuery中执行以下操作:

var subject = *string containing subject*;
parent.append("<textarea id='profile_" + subject + "_desc' name='profile[" + subject + "_desc]'></textarea");

根据我的知识,这会模仿创建字段<%= f.text_area :math_desc %><%= f.text_area :science_desc %>

但是,当我将属性math_descscience_desc传递给控制器​​中的实例变量@profile时,输入不会预先填充其值,而不像静态表单输入

我可以在视图中访问@profile.math_desc@profile.science_desc,但我希望输入在视图加载时具有这些值。

我不知道如何将ruby变量添加到append()参数中,并将变量作为属性名称。 例如append("<textarea><%= @profile.send('math_desc') %></textarea>")有效,但append("<textarea><%= @profile.send('" + subject + "_desc') %></textarea>")没有。

编辑1:

以下是我为实例分配其他属性的方法:

# NOTE: @profile.subjects contains a string representation of {"Math" => "I teach calculus", "Science" => "I have a physics degree", ...}

  def edit
     @tutor = current_tutor
     @profile = @tutor.profile
     # Call method to parse subjects JSON
     subject_parsing(@profile)
  end 

  private 
  # Decode JSON subject field into a hash
  def subject_parsing(profile)
    unless profile.subjects.blank?
      # Decode subjects into a hash
      parsed_subjects = ActiveSupport::JSON.decode(profile.subjects)
      # Extract subject names from hash into a string separated by commas
      profile.subject_names = parsed_subjects.keys.join(', ')

      parsed_subjects.each do |subj, desc| 
        subj = subj.downcase
        profile.class_eval do
          attr_accessor "#{subj}_desc"
        end
        profile.send("#{subj}_desc=", desc)
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

所以我的解决方法是使用gon gem向Javascript发送Rails哈希,然后根据subject_names数组调用主题描述。

将此添加到控制器(请参阅编辑1代码)

  # Decode JSON subject field into a hash
  def subject_parsing(tutor_profile)
    unless tutor_profile.subjects.blank?
      # Decode subjects into a hash TODO: change this because it is very slow
      gon.subjects = ActiveSupport::JSON.decode(tutor_profile.subjects)
      # Extract subject names from hash into a string separated by commas
      tutor_profile.subject_names = gon.subjects.keys.join(', ')
    end
  end

然后在Javascript中结束了这个:

var subjectNamesInput = $('#tutor_profile_subject_names');

// Initialize subject description input boxes
$.each(subjectNamesInput.tagsinput('items'), function(i, subject){
    updateSubjectInputs(subject, 'add');
});

function updateSubjectInputs(subject, action){
    var parent = $('#subject-description-inputs');

    var subject = escape(subject);

    var text = "";

    if (gon.subjects[subject] != undefined)
        text = gon.subjects[subject];

    if (action == 'add'){
        parent.append("<textarea id='tutor_profile_" + subject.toLowerCase() + "_description' name='tutor_profile[" + 
            subject.toLowerCase() + "_description]' class='form-control form-text-area' rows='5' placeholder='Add some detail about your experience with " + subject + 
            " (optional)'>" + text + "</textarea>");
    }
    else if (action == 'remove'){
        $('#tutor_profile_' + subject.toLowerCase() + '_description').remove();
    }
}

这是我认为的:

<%= f.text_field :subject_names, class: 'form-control tagsinput typeahead', placeholder: 'Subjects you teach' %>

<div id="subject-description-inputs">
</div>