ruby - 如何将自定义功能分配给 formtastic Action ?

标签 ruby formtastic

我的表格:

<%= 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

路线.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

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

最佳答案

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

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

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 操作完成什么,质疑该假设可能会让您走上更好设计的道路,但要回答您的直接问题: 在 createupdate 中检查 params[:commit] 的值应该让你走上正确的轨道。

关于ruby - 如何将自定义功能分配给 formtastic Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337698/

相关文章:

ruby-on-rails - 用于 hstore 的 simple_form 或 formtastic 输入类型

ruby-on-rails - Formtastic::FormBuilder的未定义方法 'actions'

ruby-on-rails - 使用 IP 地址结束 Rails 2 URL 会导致路由错误?

ruby - 文件循环下载列表 - net/http

java - Buildr - 使用另一个项目创建的 jar 编译项目

ruby-on-rails - 以 Form 形式向站添加 4 种饮料

ruby-on-rails - Rails 3 Formtastic。如何让 formtastic 仅显示月份和年份字段而不显示日期?

ruby-on-rails - 在 Rails3 中将 Formtastic 用于 habtm 关联的复选框

ruby-on-rails - 为什么我的 Rails 数据库迁移没有创建列?

mysql - 从belongs_to表获取Ruby中的对象集合时出错