我只能编辑我的第一篇文章

时间:2017-01-31 01:00:40

标签: ruby-on-rails ruby twitter-bootstrap

我目前面临一个奇怪的问题。我正在尝试将基本操作实现到ajax窗口中。我的问题是,当我尝试编辑牧场(如帖子)时,它总是渲染我的第一个牧场的编辑。

这是我的代码:

(牧场控制员)

 before_action :set_ranch, only: [:show, :edit, :update, :destroy]

  def index
    @ranches = current_user.ranches
  end

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

(牧场/指数)

  <%- @ranches.each do |ranch| %>

    <div class="box panel panel-default">
      <h2><%=link_to ranch.name, ranch%></h2>
      <div class="image_wrapper">
        <%= link_to (image_tag "ranch.jpg"), ranch %>
      </div>
      <button type='button' class='btn btn-default' data-toggle='modal' data-target='#MyEditRanch' aria-hidden="true" remote="true" style="float:right; margin-top: 10px;">
      <i class="fa fa-cog"></i>

      </button>
    </div>  


    <!-- modal Edit -->
    <div id='MyEditRanch' class='modal fade' role='dialog' aria-hidden="true">
      <div class="modal-dialog">
        <div class='content'>
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h3 class="modal-title">Edit <%=ranch.name%></h3>
          </div>
          <div class="modal-body">
            <%= render 'form2', ranch: ranch%>

          </div>
        </div>
      </div>
    </div>
    <!-- /modal Edit -->
  <%end%>

(&amp; my _form2)

<%= simple_form_for(ranch) do |f| %>
  <%= f.error_notification %>
  <% if ranch.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(ranch.errors.count, "error") %> prohibited this ranch from being saved:</h2>

      <ul>
      <% ranch.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="col-lg-6">
    <div class="input-group" style=" margin-left: 70px;">

      <div class="input" style="width: 400px; margin-top: -10px; text-align: center;" >
        <%= f.input :name, label: false, style:"margin:0px;", placeholder: "Name of your ranch"%>
      </div><!-- /btn-group -->

    </div><!-- /input-group -->

      <div class="form-actions" style="max-width: 300px">
        <%= f.button :submit, style:"text-align:center; margin-left: 70px;" %>
      </div>

      <%= link_to "Delete", ranch_path(ranch), method: :delete, data: {confirm: "Are you sure that you want to delete this ranch ?"}, class: "btn btn-danger", style:"margin-left: 140px;" %>
<% end %>

  </div>

所以,如果你有任何建议来解决这个问题,那么欢迎你!

提前致谢

1 个答案:

答案 0 :(得分:2)

在HTML中,ID必须在页面上唯一。

即必须只有其中一个......

这意味着必须只有一个ID为MyEditRanch的div ... 有时浏览器会让你逃脱...但如果你有JS使用该id(例如切换模态)......它仍然会在页面上寻找该id的第一个实例来切换..即只是他第一个。

如果你想要显示多个牧场 - 每个牧场都有自己的编辑模式......那么你真的必须给每个人一个自己独特的id来切换。

例如,在按钮和编辑模式中将牧场的id附加到它。例如

<button type='button' data-toggle='modal' data-target='#edit-ranch-<%= ranch.id %>' ...

<!-- and later -->
<div id='#edit-ranch-<%= ranch.id %>'