加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何为formtastic行动分配自定义功能?

发布时间:2020-12-17 07:10:08 所属栏目:百科 来源:网络整理
导读:我的表格: %= 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 sa
我的表格:

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

而我唯一不理解的是,在行动中要写这个函数.

解决方法

我不确定你正在尝试用save_and_new动作做什么,但我可以告诉你为什么你没有触发它.

默认情况下,使用semantic_form_for创建formtastic的表单将使用RESTful约定,即为新记录执行create操作,为现有记录执行更新操作.如果您使用第一个提交按钮(标记为“保存”)成功点击了创建/更新操作,但是您希望第二个“保存和新建”按钮执行不同的操作,则需要检查参数的值[ :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]的值在创建或更新中应该让你在正确的轨道上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读