重构 Rails 视图
我是 Rails 开发的新手,所以请耐心等待。我正在创建一个视图,其中有几个看起来非常相似的字段。它只是请求以某种方式重构,但我一直无法弄清楚。请参阅下面的代码示例:
<%= form_for(@tapelog) do |f| %>
<div class="container">
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :client %>
</div>
<div class="span-8 last">
<%= f.collection_select :client_id, Client.find(:all), :id, :name,
{ :prompt => "Select a Client..." },
{ :class => "automatixSelect" } %>
</div>
</div>
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :employer %>
</div>
<div class="span-8 last">
<%= f.collection_select :employer_id, Employer.find(:all), :id, :name,
{ :prompt => "Select an Employer..." },
{ :class => "automatixSelect" } %>
</div>
</div>
....
<% end %>
大约有 7 个这样的字段。我试图将它们全部放入部分中,这样我就可以减少此页面上的混乱,但由于未定义“f”,所以出现错误。关于如何减少这里的一些混乱有什么想法吗?任何其他有关 Ruby 重构的一般提示也将受到欢迎。
谢谢, ——A.
I'm new to Rails development, so please bear with me. I'm creating a view that has several fields on it that look very similar. It's just begging to be refactored somehow but I haven't been able to figure it out. See code sample below:
<%= form_for(@tapelog) do |f| %>
<div class="container">
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :client %>
</div>
<div class="span-8 last">
<%= f.collection_select :client_id, Client.find(:all), :id, :name,
{ :prompt => "Select a Client..." },
{ :class => "automatixSelect" } %>
</div>
</div>
<div class="field span-16">
<div class="span-8 labelRight">
<%= f.label :employer %>
</div>
<div class="span-8 last">
<%= f.collection_select :employer_id, Employer.find(:all), :id, :name,
{ :prompt => "Select an Employer..." },
{ :class => "automatixSelect" } %>
</div>
</div>
....
<% end %>
There are about 7 fields like that. I tried to put them all into partials just so I could reduce the clutter on this page but that errors out because 'f' is not defined. Any ideas on how I could reduce some of the clutter here? Any other tips in general on Ruby refactoring would also be welcome.
Thanks,
-- A.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想在后续部分中使用“f”,请将其作为参数传递
If you want to use the 'f' in the subsequent partials, pass it as a parameter
为了清楚起见,我要做的第一件事是将“f”局部变量重命名为“form”。然后,将代码提取到部分是合理的:
在我看来,这是一个belongs_to关系,所以我可以创建一个名为“belongs_to”的部分并将其呈现为:
我们的想法是我们将有一个名为“parent”的本地我们可以部分改变。请注意,我使用了速记部分语法。它等同于:
The first thing I'd do is rename the "f" local variable to "form" for clarity. Then, extracting the code to a partial is reasonable:
It looks to me like this is a belongs_to relationship, so I might create a partial called "belongs_to" and render it like:
The idea is we'll have a local named "parent" that we can alter in the partial. Note that I used the shorthand partial syntax. It's the same as: