简体   繁体   English

Rails:activeadmin重写创建操作

[英]Rails: activeadmin overriding create action

I have an activeadmin resource which has a belongs_to :user relationship. 我有一个activeadmin资源,它具有belongs_to:user关系。

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 

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). 我只是希望将@item变量分配给用户然后调用super将起作用(并且确实如此)。 I also started looking through the gem but couldn't see how it was actually working. 我也开始浏览宝石,但看不出它是如何工作的。

Any pointers would be great. 任何指针都会很棒。 I'm assuming this is something that InheritedResources gives you? 我假设这是InheritedResources给你的东西?

Thanks! 谢谢!

I ran into a similar situation where I didn't really need to completely override the create method. 我遇到了类似的情况,我真的不需要完全覆盖create方法。 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源代码后,我确定我可以使用before_create来完成我需要的操作:

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

Another option: 另外一个选项:

def create
  params[:item].merge!({ user_id: current_curator.id })
  create!
end

你是对的主动管理员使用InheritedResources ,你可以在页面的末尾看到所有其他工具。

As per the AA source code this worked for me: 根据AA 源代码,这对我有用:

controller do
  def call_before_create(offer)
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM