在控制器操作内部重构 params[...] 的许多 if 语句
我有这样的代码,用于在我的表单中进行链选择 查看索引操作:
<%= form_tag do %>
<%= collection_select(*@brands_select_params) %>
<%= collection_select(*@car_models_select_params) %>
<%= collection_select(*@production_years_select_params) %>
<% # Пока еще никто ничего не выбрал %>
<%= submit_tag "Send", :id => "submit", :name => "submit" %>
和我的控制器:
class SearchController < ApplicationController
def index
@brands = Brand.all
@car_models = CarModel.all
if (params[:brand].blank?)
@brands_select_params = [:brand, :id, @brands, :id, :name, :prompt => "Выбирай брэнд"]
if params[:car_model].blank?
@car_models_select_params = [:car_model, :id, @car_models, :id, :name, { :prompt => "Model" }, \
{ :disabled => "disabled" }]
@production_years_select_params = [:production_year, :id, @car_models, :id, :name, { :prompt => "Year" }, \
{ :disabled => "disabled" }]
end
else
@brands_select_params = [:brand, :id, @brands, :id, :name, { :selected => params[:brand][:id] } ]
if params[:car_model].blank?
@car_models_select_params = [:car_model, :id, Brand.find(params[:brand][:id]).car_models, :id, :name, \
{ :prompt => "And model now" } ]
@production_years_select_params = [:production_year, :id, @car_models, :id, :name, { :prompt => "Year" }, \
{ :disabled => "disabled" } ]
else
@car_models_select_params = [:car_model, :id, Brand.find(params[:brand][:id]).car_models, :id, :name, \
{ :selected => params[:car_model][:id] } ] unless params[:car_model][:id].empty?
@production_years_select_params = [:production_year, :id, CarModel.find(params[:car_model][:id]).production_years, :id, :year, \
{ :prompt => "And year now" } ] unless params[:car_model][:id].empty?
end
end
end
end
如您所见,我的控制器代码中有太多 if 语句。我会在那里添加更多条件。此后,任何读过该代码的人都会受到大脑损坏。所以我只想以真正的 Ruby 方式实现它,但不知道如何。请帮忙,伙计们。我应该如何重构这堆废话?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为问题的很大一部分是你在控制器中做了太多的事情。生成标记(以及 IMO,包括为表单助手构建参数列表)应该在视图和视图助手中完成。所以:
然后你可以将你的控制器缩减为这样:
在你看来:
我怀疑你可以使用
form_for
和fields_for
并完全摆脱助手,但这在一定程度上取决于模型关联的设置方式。I think a big part of the problem is you're doing too much in your controller. Generating markup (and IMO that includes building parameter lists for form helpers) should be done in views and view helpers. So:
Then you can cut your controller down to this:
And in your view:
I suspect you could simplify this even more using
form_for
andfields_for
and get rid of the helpers entirely, but it depends a bit on how your model associations are set up.此类问题没有明显的解决方案。
一般来说,我尝试保持
if
/else
架构非常清晰,并将所有代码导出到单独的方法中。这里有两个优点:可读性
更容易的单元测试
对于您的情况,这将是:
There is no obvious solution to this kind of problem.
Generally, I try to keep the
if
/else
architecture very clear and export all code into separate methods. 2 advantages here:readability
easier unit testing
For your case, it would be: