Ruby-on-rails Rails:activeadmin 覆盖创建操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13675765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: activeadmin overriding create action
提问by patrickdavey
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). I also started looking through the gem but couldn't see how it was actually working.
但是 ;) 我只是想知道这是如何工作的?我只是希望将 @item 变量分配给用户然后调用 super 会起作用(确实如此)。我也开始查看 gem,但看不到它的实际工作原理。
Any pointers would be great. I'm assuming this is something that InheritedResources gives you?
任何指针都会很棒。我假设这是 InheritedResources 给你的东西?
Thanks!
谢谢!
回答by Karl Wilbur
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_createto do what I needed:
我遇到了类似的情况,我真的不需要完全覆盖 create 方法。我真的只想在保存之前注入属性,并且只在创建时注入;与您的示例非常相似。在阅读了 ActiveAdmin 源代码后,我确定我可以before_create用来做我需要的事情:
ActiveAdmin.register Product do
before_create do |product|
product.creator = current_user
end
end
回答by Kori John Roys
Another option:
另外一个选项:
def create
params[:item].merge!({ user_id: current_curator.id })
create!
end
回答by zolter
回答by justinsAccount
As per the AA source codethis worked for me:
根据 AA源代码,这对我有用:
controller do
def call_before_create(offer)
end
end

