【问题标题】:How to assign custom function to formtastic action?如何将自定义功能分配给格式动作?
【发布时间】:2012-04-26 16:39:23
【问题描述】:

我的表格:

<%= semantic_form_for(@campaign) do |f| %>
...
  <%= f.actions do %>
    <%= f.action :submit, label: "Save"%>
    <%= f.action :submit, label: "Save & New" %>
    <%= f.action :cancel, label: "Cancel"%>
  <% end %>
<% end %>

campaign_controller.rb 中的函数:

  def save_and_new
    print 'SAVE_AND_NEW'
    @campaign = Campaign.find(params[:id])

    respond_to do |format|
      if @campaign.update_attributes(params[:campaign])
        format.html { redirect_to new_campaign_path, notice: 'Campaign was successfully usaved.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @campaign.errors, status: :unprocessable_entity }
      end
    end
  end

Routes.rb:

  resources :campaigns do 
    member do
      post 'save_and_new'
    end
  end

路线,根据功能:

save_and_new_campaign POST   /campaigns/:id/save_and_new(.:format) campaigns#save_and_new

而我唯一不明白的是,在调用函数时要写什么。

【问题讨论】:

    标签: ruby formtastic


    【解决方案1】:

    我不确定你到底想用save_and_new 操作做什么,但我可以告诉你为什么你没有触发它。

    默认情况下,您使用 semantic_form_for 使用 formtastic 创建的表单将使用 RESTful 约定,即为新记录点击 create 操作,为现有记录点击 update 操作。如果您使用第一个提交按钮(标记为“保存”)成功点击了create/update 操作,但您希望第二个“保存和新建”按钮执行不同的操作,则需要检查值params[:commit] 在控制器中分叉您对提交的处理。也许一些代码会更清楚。假设您正在提交更新现有记录:

    def create
      if params[:commit] == "Save"
        # code for handling "Save" scenario
      else
        # code for handling "Save & New" scenario, perhaps even directly call:
        save_and_new
      end
    end
    
    
    def update
      if params[:commit] == "Save"
        # code for handling "Save" scenario
      else
        # code for handling "Save & New" scenario, perhaps even directly call:
        save_and_new
      end
    end
    

    再次,我不清楚您试图通过 save_and_new 操作完成什么,并且质疑该假设可能会让您走上更好设计的道路,但要回答您的直接问题:检查价值params[:commit] in createupdate 应该会让你走上正轨。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多