What's the rails way to load other models collections for new, edit update and create actions?

戏子无情 提交于 2019-12-02 04:13:19

In your controller, or if needed elsewhere, in application_controller.rb:

def all_categories
  @all_categories ||= Category.all
end
helper_method :all_categories

The first time it's called, it will hit the db, and later it will return the controller instance variable.

I would prefer your third solution. I don't like using business logic in view, because I guess gathering information is the controller's task, in the view layer I just want to use the data and the helper methods. Using Category.all in the view layer can be good when you're using cache, but in this case you should send an expired signal somehow if it changed.

Your first solution has many repeated lines, which you can erase by using your third solution. So I would choose the third one :)

I'd go for the first option in this case.

Edit

As I've mentioned in the comments, it depends on the situation. A relatively clean way for me would be to define a categories method in the controller and declare it a helper. Then call that when you need it in the view.

However (and this is the situation I envisaged when first answering) if it's a single form field I'd simply call the model from the view just for the sake of simplicity - methods like

helper_method :all_categories
private
def all_categories
  Category.all
end

aren't exactly the most elegant code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!