27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

486 CHAPTER 17 Engines<br />

This code has defined a Forem::TopicsController, which inherits seemingly from<br />

ApplicationController. This is actually Forem::ApplicationController because<br />

the class is being defined in the Forem module. The Forem::ApplicationController<br />

will be where you put all your engine’s common controller things later on.<br />

Right now, you need to define this missing index action. This action needs to<br />

retrieve a list of all topics and then show them in the view. You’ll define this action by<br />

changing your Forem::TopicsController to what’s shown in the following listing.<br />

Listing 17.3 app/controllers/forem/topics_controller.rb<br />

module Forem<br />

class TopicsController < ApplicationController<br />

def index<br />

@topics = Forem::Topic.all<br />

end<br />

end<br />

end<br />

You’re namespacing your reference to the Forem::Topic model because it’s actually<br />

Ruby that will be loading this class. If you referenced it without the Forem:: prefix,<br />

then it would go looking for a normal Topic model that may belong to your application<br />

or another engine. 19 At this point, you’re not going to have the Forem::Topic<br />

model defined, and so you’ll need to generate that too. It will need to have a subject<br />

attribute, as well has having a user_id attribute, which you’ll fill out later:<br />

rails g model topic subject:text user_id:integer<br />

As when you generated the topics controller, this model will also be namespaced. The<br />

migration it generates is called create_forem_topics and will create a table called<br />

forem_topics. This means the migration, model, and table will not clash with any similarly<br />

named migration, model, or table in the main application.<br />

To run this migration, run rake db:migrate as you would in an application. In an<br />

engine, this will run the migration against the dummy application’s development database.<br />

There’s no rake db:test:prepare in engines at the moment, and so you’ll have<br />

to work around this by changing the dummy application’s config/database.yml file to<br />

make the development and test databases the same. You’ll do this by using the code in<br />

the following listing.<br />

Listing 17.4 spec/dummy/config/database.yml<br />

shared: &shared<br />

adapter: sqlite3<br />

database: db/development.sqlite3<br />

pool: 5<br />

timeout: 5000<br />

development:<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!