【问题标题】:How to pre-populate dynamically added form inputs in Rails如何在 Rails 中预填充动态添加的表单输入
【发布时间】:2015-07-26 19:03:46
【问题描述】:

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

例如<%= f.text_field :name %> 将从 @profile.name 预填充其值。

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

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

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

所以如果@profile.subjects 包含“数学”和“科学”,我会在 jQuery 中执行以下操作:

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

据我所知,这将模拟创建字段 &lt;%= f.text_area :math_desc %&gt;&lt;%= f.text_area :science_desc %&gt;

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

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

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

编辑 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

【问题讨论】:

  • 您可以直接为您的控制器添加代码吗?这让我头疼。
  • 我在最新的编辑中添加了如何在控制器中分配属性的代码。
  • 你能把整个东西都加进去吗?代码易于阅读。人们试图告诉你什么代码没有那么多。
  • 我对 EDIT 1 中的代码进行了更改以包含实际的编辑操作。

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


【解决方案1】:

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

将此添加到控制器(参见 EDIT 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 2011-11-15
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多