如何在自定义控制器生成器中获取GeneratedAttribute?
我正在创建一个派生自 Rails::Generators::NamedBase 的自定义控制器生成器,它创建给定特定模型名称(例如 Person)的控制器和视图。我还想创建一个 _form.html.haml 部分,它根据模型的属性构建表单(我正在使用 simple_form 顺便说一句)。
到目前为止我所得到的是:
<% attributes = file_name.capitalize.constantize.columns.map { |c| [Rails::Generator::GeneratedAttribute.new(c.name, c.type)]} %>
- simple_form_for [:admin,@<%=file_name%>] do |f|
= render 'shared/error_summary', :object => f.object
.inputs
<%- attributes.each do |attribute| -%>
= f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %>
<%- end -%>
.actions
= f.button :submit
我收到一个“未初始化的常量 Rails::Generator (NameError)”异常。不确定我需要什么,或者我上面的方法是否正确。
任何帮助都会很棒。
谢谢-wg
I'm creating a custom controller generator that derives from Rails::Generators::NamedBase that creates both a controller and views given a particular model name (e.g. Person). I also want to create a _form.html.haml partial that builds a form based on the model's attributes (I'm using simple_form btw).
What I have so far is:
<% attributes = file_name.capitalize.constantize.columns.map { |c| [Rails::Generator::GeneratedAttribute.new(c.name, c.type)]} %>
- simple_form_for [:admin,@<%=file_name%>] do |f|
= render 'shared/error_summary', :object => f.object
.inputs
<%- attributes.each do |attribute| -%>
= f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %>
<%- end -%>
.actions
= f.button :submit
I'm getting an "uninitialized constant Rails::Generator (NameError)" exception. Not sure what I need to require or if my approach above is even right.
Any help would be awesome.
Thanks -wg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑问题是你在 Generator 后面缺少了 s 。正确的方法调用是:
不要在模板中创建属性变量,最好在生成器类的初始化方法中创建它。该方法的框架如下所示:
如果您要让用户以“column_name:column_type”的形式传入所需的属性,那么您可以执行以下操作:
您可能还希望以某种方式处理没有传入任何属性的可能性。然而,这将取决于您的需求,因此如果没有更多信息,我无法指导您。对不起!
一个值得遵循的良好模型标准是 nifty_generators来源。
I suspect the problem is that you are missing an s after Generator. The correct method call is:
Instead of creating your attributes variable inside your template, it is better to create it inside your generator class in the initialize method. This method looks like this as a skeleton:
If you are getting your user to pass in the desired attributes in the form column_name:column_type then you can do the following:
You might want to also handle the possibility that no attributes are passed in somehow. This will depend on your needs however so I can't guide you on that without more information. Sorry!
A good model standard to follow is the nifty_generators source.