2014-02-12 54 views
4

我想在我的用户activeadmin页面上实现一个自定义操作(notify_all),点击时将显示一个表单,当提交时将路由到另一个自定义操作(send_notification_to_all)。到目前为止,我一直无法得到第二部分的工作。Activeadmin自定义操作和表单

管理/ users.rb的:

ActiveAdmin.register User do 

    action_item :only => :index do 
    link_to 'Notify All', notify_all_admin_users_path 
    end 

    collection_action :notify_all, :method => :get do 
    puts "notifying...." 
    end 

    collection_action :send_notification_to_all, :method => :post do 
    puts "sending notification...." 
    end 



end 

通知时点击All按钮,如下图的呈现方式。 的意见/管理/用户/ notify_all.html.erb

<form action="send_notification_to_all" method="post"> 
    <div><textarea rows="10" cols="100" placeholder="Enter message here"></textarea></div> 
    <div><input type="submit"></div> 
</form> 

当表单提交,我得到一个401错误未经授权:

Started POST "/admin/users/send_notification_to_all" for 127.0.0.1 at 2014-02-12 14:08:27 -0600 
Processing by Admin::UsersController#send_notification_to_all as HTML 
WARNING: Can't verify CSRF token authenticity 
    AdminUser Load (0.8ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = 1 LIMIT 1 
    (0.3ms) BEGIN 
    (26.6ms) UPDATE "admin_users" SET "remember_created_at" = NULL, "updated_at" = '2014-02-12 14:08:27.394791' WHERE "admin_users"."id" = 1 
    (20.3ms) COMMIT 
Completed 401 Unauthorized in 108.3ms 

是否有可能做什么,我试图做虽然活跃的管理?

回答

3

找到类似问题的答案here

我修改的形式包括认证令牌如下:

<form action="send_notification_to_all" method="post"> 
    <input type="hidden" name="authenticity_token" value="#{form_authenticity_token.to_s}"> 
    <div><textarea rows="10" cols="100" placeholder="Enter message here"></textarea></div> 
    <div><input type="submit"></div> 
</form> 

这解决了这个问题。

6

使用Rails,Formtastic或ActiveAdmin表单构建器将完全避免该问题,因为它会自动为您呈现真实标记。

使用Formtastic的semantic_form_for表单生成器重写您的形式:

<%= semantic_form_for :notification, url: { action: :send_notification } do |f| %> 

    <%= f.inputs do %> 
    <%= f.input :content, as: :text, input_html: { placeholder: "Enter message here" } %> 
    <%- end %> 

    <%= f.actions %> 
<%- end %> 

这可能是值得通过Formtastic的documentation了解更多详情阅读。 ActiveAdmin默认包含Formtastic。

+0

我没有通知模型,是否可以在没有模型的情况下使用formtastic? – septerr

+1

是的,上面使用的符号':notification'只是命名空间由表单发送的参数。它不需要数据模型。在你的行动中,你可以通过'params [:notification] [:content]'来访问通知内容。 –