Rails:ActiveAdmin覆盖创建动作 [英] Rails: activeadmin overriding create action

查看:68
本文介绍了Rails:ActiveAdmin覆盖创建动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个activeadmin资源,该资源具有一个belongs_to:user关系。

I have an activeadmin resource which has a belongs_to :user relationship.

当我在活动admin中创建模型的新实例时,我想关联当前作为创建实例的用户登录的用户(我想像是非常标准的东西)。

When I create a new Instance of the model in active admin, I want to associate the currently logged in user as the user who created the instance (pretty standard stuff I'd imagine).

所以...我可以使用它:

So... I got it working with:

controller do
  def create
    @item = Item.new(params[:item])
    @item.user = current_curator
    super
  end 
end 

但是)我只是想知道这是如何工作的?我只是希望为用户分配@item变量,然后调用super将起作用(并且确实如此)。我也开始浏览宝石,但看不到宝石的实际工作原理。

However ;) I'm just wondering how this works? I just hoped that assigning the @item variable the user and then calling super would work (and it does). I also started looking through the gem but couldn't see how it was actually working.

任何指针都很棒。我假设这是InheritedResources给您的东西?

Any pointers would be great. I'm assuming this is something that InheritedResources gives you?

谢谢!

推荐答案

我遇到了类似的情况,我实际上并不需要完全覆盖create方法。我真的只想在保存之前注入属性,并且只在创建时注入;与您的示例非常相似。阅读完ActiveAdmin的源代码后,我确定可以使用 before_create 来完成所需的操作:

I ran into a similar situation where I didn't really need to completely override the create method. I really only wanted to inject properties before save, and only on create; very similar to your example. After reading through the ActiveAdmin source, I determined that I could use before_create to do what I needed:

ActiveAdmin.register Product do
  before_create do |product|
    product.creator = current_user
  end
end

这篇关于Rails:ActiveAdmin覆盖创建动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆