简体   繁体   中英

How can we use One controllers method in other controllers view?

I have two controllers named: lists_controller.rb and articles_controller.rb .

And a view under articles/index.html.rb .

I want to use a element from list_controller.rb in articles/index.html.rb . My method in lists_controller.rb is as follows:

def index
    @lists = List.all
end

I want to use @lists in articles/index.html.rb to loop over the elements under @lists instance in the articles/index.html.rb view under articles_controller.rb

The easiest way is to simply add @lists = List.all to ArticlesController#index . It's hardly enough code to worry about duplication/DRY.

Were more complex behavior required, you can share behavior among controllers by defining it in ApplicationController (from which controllers inherit), or among multiple actions within a controller using filters , or by combining the two.

To answer the title literally - you could create a module with a method called list_index and then include that module in both controllers.

In your particular case it's probably be easier to just have the two calls as others have outlined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM