【问题标题】:Rails 4 Replace words occurrences with form in post bodyRails 4用帖子正文中的形式替换单词出现
【发布时间】:2015-09-08 12:57:29
【问题描述】:

我需要替换 '--' 和 '--' 之间的每个单词,每个单词都可以提取为:

labels = @post.body.scan(/--(.+?)--/).flatten

但是,我不知道如何生成替换单词的表单(我认为将每个单词用作标签)。像这样的东西(但确实有效):

    <% if labels.length > 0 %>

    <strong> <%= 'Replace labels' %> </strong>

    <%= form_tag do %> 

      <% num = 0 %> 

      <%  labels.length.times do %>

      <p>
        <%= label_tag labels[num] %><br>
        <%= text_field_tag labels[num] %>
        <% num = num + 1 %>
      </p>

      <%end%>

      <p>
        <%= submit_tag ("Replace") %>
      </p>

    <% end %>
<% end %>

@post.body = "--Lorem ipsum-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et --dolore-- magna 阿里夸Ut enim ad minim veniam, quis nostrud exercitation ullamco Laboris nisi ut aliquip ex ea commodo consequat。 --Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariaatur。”

标签 [--Lorem ipsum--、--dolore--、--Duis aute--]

在这种情况下,表单包含三个标签和文本字段,用于输入文本以替换标签。

【问题讨论】:

  • 换成什么?
  • 替换为通过表单输入的内容
  • 你能举个例子说明@post.body包含什么吗?
  • 请将其添加到问题中。
  • @maxcal 完成!我已经添加了

标签: ruby-on-rails regex gsub


【解决方案1】:

已编辑。

我认为更简单的解决方案可能只是使用 javascript 将文本字段与每个标签的输入链接:

$(function(){
    var $label_holder = $('#post_labels'),
        $post_body = $('#post_body'),
        tag = /--(.+?)--/g,
        delimiter = /--/g;

    // When the label inputs change
    // Update the body
    $label_holder.on('change keyup', 'input', function(){
        var new_label = '--' + $(this).val() + '--';
        var text = $post_body.val();
        var old_label = text.match(tag)[$(this).index()];
        $post_body.val(text.replace(old_label, new_label));
    });

    // When the body changes
    // Update the label inputs
    $post_body.on('change, keyup', function(){
        var labels = $post_body.val().match(tag);
        labels = $.map(labels, function(str){ return str.replace(delimiter, '') });
        $label_holder.empty();
        // This creates an input for each label
        $(labels).each(function(i, val){
            var input = document.createElement('input');
            input.name = 'labels[' + i + ']';
            input.value = val;
            $label_holder.append(input);
        });
    }).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="edit_post" id="edit_post_5" action="/posts/5" accept-charset="UTF-8" method="post">

  <div class="field">
    <label for="post_body">Body</label><br>
    <textarea name="post[body]" id="post_body" style="margin: 0px; height: 168px; width: 150px;">--Lorem asd-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
--asd-- magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
--Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur
    </textarea>
  </div>

  <fieldset>
    <legend>Labels</legend>
    <div class="field" id="post_labels"><input name="labels[0]"><input name="labels[1]"><input name="labels[2]"></div>
  </fieldset>

  <div class="actions">
    <input type="submit" name="commit" value="Update Post">
  </div>
</form>

按下运行 sn-p 按钮并尝试一下。

rails 表单如下所示:

<%= form_for(@post) do |f| %>
  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>

  <fieldset>
    <legend>Labels</legend>
    <div class="field" id="post_labels">
    </div>
  </fieldset>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

由于我们在 javascript 中编辑所有标签并发送更新的post[body],因此我们不必关心 rails 中的标签。

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  def index
    @posts = Post.all
  end

  # GET /posts/1
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  def create
    @post = Post.new(post_params)

    if @post.save
      redirect_to @post, notice: 'Post was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /posts/1
  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /posts/1
  def destroy
    @post.destroy
    redirect_to posts_url, notice: 'Post was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def post_params
      params.require(:post).permit(:body)
    end
end

【讨论】:

  • 感谢您的回复!我会尝试你的建议,使用哈希而不是数组似乎是正确的方法。如果您可以更明确地说明大会或分享链接,我将不胜感激!
  • 我的想法是,如果你使用一个数组并且其中一个标签是空的,例如它会抛出排序。不确定这是否真的是一个问题。这就是hash.key?(i) ? hash[i] : str 部分存在的原因。
  • 很遗憾,我缺乏经验,无法实施您的回答,但感谢您的回答!
  • 我用更简单的解决方案编辑了这个问题。在写作时,我搭建了一个 Rails 应用程序,你可以在这里看到 github.com/maxcal/sandbox/tree/replace-words-occurrences
  • 你太棒了!非常感谢您的耐心和奉献。
猜你喜欢
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2013-03-25
相关资源
最近更新 更多