Using multiple controllers in one view in Rails

前端 未结 3 709
抹茶落季
抹茶落季 2020-12-28 23:29

I\'m working on something like a social networking mesh; I am using different API\'s from various websites, e.g. Last.FM, Delicious, Twitter, ...

I\'ve created one c

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 23:52

    First off, you should put all of the data-storing and data-gathering methods into Resources and Models so they are accessible from all controllers. You can keep the internal data-mutating operations in your individual controllers though. Once you have it organized like this, you could do what Hobo does: create a controller just for the front page, "front_controller" if you will. Here you can display data gathered from all of your models and resources, as well as links to your other controller actions.

    These are a few interesting thoughts on better organizing your models and controllers (fat models, skinny controllers is a rule of thumb. Since you said you are using other API's (like lastfm and twitter), you might want to take a look at this railscasts about creating non ActiveRecord models (models that are not tied to a database)

    here is some pseudo code, keep in mind its really only targeted at your question.

    #  pseudo code  
    
      class TwitterController < ApplicationController
        def index
          @services = {
            :twitter => TwitterModel.find(:all, ...),
          }
        end
        def update_twitter
          TwitterUpdaterClass.update { |twit|
            _m = TwitterModel.new 
            _m.message = twit.msg
            _m.from = twit.from
            # ..
            _m.save
          }
        end
      end
    
    
      class MyIndexController < ApplicationController
        def index
          @services = {
            :twitter => TwitterModel.find(:all, ...),
            :lastfm => LastFmModel.find(:all, ...)
          }
        end
      end
    

    it might be much better to have background-workers update your rest-services instead a controller which you need to invoke every time you want to fetch recent tweets. here is nice article showing - 6 ways to run background jobs in rubyonrails

      # more pseudo code
    
      class TwitterWorker < BackgrounDRb::MetaWorker
        set_worker_name :twitter_worker
        def create(args = nil) # instead of TwitterController.update_twitter
          TwitterUpdaterClass.update { |twit|
            _m = TwitterModel.new 
            _m.message = twit.msg
            _m.from = twit.from
            # ..
            _m.save
          }
        end
      end
    

提交回复
热议问题