【问题标题】:Rails Form Renders TwiceRails 表单渲染两次
【发布时间】:2012-07-02 19:59:42
【问题描述】:

有时当我提交表单然后返回浏览器时,它会呈现整个表单两次(见屏幕截图)。不确定是我的视图或控制器代码导致了这种情况,但我似乎无法弄清楚。

谢谢

occasions_controller.rb

  def create
     @user = current_user
     @occasion = Occasion.new(params[:occasion])
     @occasion.user = User.find(current_user.id)
     if @occasion.save
      redirect_to occasions_path
    else
      render :new
    end
  end

user_steps/occasions.html.erb

<%= simple_form_for @user, url: wizard_path do |f| %>
  <div id="single_module">
  <div class="pitch">
   <h2 class="signup">Step 3: Your first Occasion!</h2>
  </div>
  <div id="input1" style="margin-bottom:4px;" class="clonedInput">
    <p>*Just one to get you started, after completion of the sign up process you will have a chance to utilize our occasion wizard to add as many events as you like! (exciting, we know)</p>
    <ul class="testss1">
      <%= f.simple_fields_for :occasions do |occasion_o| %>
        <li><%= occasion_o.input :name, :placeholder => 'Enter occasion Name', :hint => ('Examples: Anniversaries, Birthdays, Graduations, Mothers day, Fathers day, Valentines day, Weddings, Holidays') %></li>
        <li><%= occasion_o.input :pname, :label => 'Persons Name', :placeholder => '(optional)' %></li>
        <li><%= occasion_o.input :dateg, :label => 'Date',:as => :date_picker, :input_html => { :class => 'special' } %></li>
        <li><%=  occasion_o.input :recurring, :as => :radio_buttons, :label => 'Remind me of this event every year?' %></li>
    <h3>Top 3 Interests</h3>

        <li class="tes1"><%= occasion_o.association :interests, :label => false, :as => :check_boxes %></li></ul>
    <%end%>
    </br>
    </div>
      <%= link_to "skip this step", next_wizard_path %>
      <%= f.button :submit, 'Submit' %>
     </br>
     </br>
     </br>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 erb simple-form


    【解决方案1】:

    您的用户似乎有两个与之相关的场合。我会在您的控制器中使用 puts 语句检查场合的长度并检查您的日志:

      def create
         @user = current_user
         puts "The current length of occasions is #{ @user.occasions.length }"
         @occasion = Occasion.new(params[:occasion])
         @occasion.user = User.find(current_user.id)
         if @occasion.save
          redirect_to occasions_path
        else
          render :new
        end
      end
    

    【讨论】:

    • 是的。如何防止它在提交后添加一个新的,然后单击下一页上的后退按钮?
    • 问题出在您的&lt;%= simple_form_for @user, ... 代码中。当您呈现该视图时,它将为您的所有场合呈现一个表单。如果该表单的目的只是创建一个新场合,那么您应该只在控制器中设置@occasion 而不要传递@user。我还要去掉f.simple_fields_for :occasions do |occasion_o| 循环。只需在其位置上执行 &lt;%= simple_form_for(@occasion) do |f| %&gt;... 即可。见documentation
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多