[英]How do I execute a Ruby command when a link_to is pressed?
Basically, what I want to do is run a FactoryGirl.create
whenever a link_to
is pressed. 基本上,我想做的
FactoryGirl.create
每当按下link_to
时运行FactoryGirl.create
。
Right now, every time I want to generate a new object in my DB, I have to go into Rails Console and type: FactoryGirl.create(:object)
. 现在,每次我想在数据库中生成一个新对象时,都必须进入Rails Console并输入:
FactoryGirl.create(:object)
。
But, ideally...I would love to be able to execute that from the link_to
. 但是,理想情况下...我希望能够从
link_to
执行该操作。
Not sure how to do that though. 虽然不知道如何做到这一点。
Thoughts? 有什么想法吗?
I suppose you could treat the creation of an object via FactoryGirl like any other RESTful resource with a dedicated controller and routes: 我想您可以像其他任何RESTful资源一样通过FactoryGirl处理通过专用控制器和路由创建对象的情况:
class MyFactoryGirlController
def create
if FactoryGirl.create(:object)
# Do something
end
end
end
routes.rb routes.rb
post '/someroute', to: 'myfactorygirl#create', as: :factory_girl
And your link: 和您的链接:
link_to "Create an object", factory_girl_path(object: 'SomeObject'), method: :post
Note that this code is meant to illustrate a concept and is incomplete. 请注意,此代码仅用于说明概念,并且不完整。 Copy and pasting will not work.
复制和粘贴将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.