27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

488 CHAPTER 17 Engines<br />

You’re missing the new action in your Forem::TopicsController. This action will provide<br />

the form that users can use to create a new topic.<br />

17.5.5 The new action<br />

You need to define the new action in the controller. This action and its related view will<br />

provide the form for creating a topic and its first post. In this brand new action, you can<br />

initialize a new topic and post with the following code underneath the index action:<br />

def new<br />

@topic = Forem::Topic.new<br />

@topic.posts.build<br />

end<br />

There’s no association definition or even a model for the posts association yet, and so<br />

you should create the model and then the correct associations. You can do this by running<br />

this command:<br />

rails g model post topic_id:integer text:text user_id:integer<br />

You can then run rake db:migrate to create the forem_posts table. Next, you need to<br />

set up both ends of this association, beginning with the Forem::Post model, which<br />

needs to have this line inserted:<br />

belongs_to :topic<br />

Here you don’t need to tell Rails that the class of this association is Forem::Topic,<br />

Rails will figure that out itself. In the Forem::Topic model, you need to set up the<br />

other end of this association and accept nested attributes for it:<br />

has_many :posts, :order => "created_at ASC"<br />

accepts_nested_attributes_for :posts<br />

You’re putting the accepts_nested_attributes_for in the Forem::Topic model<br />

because when you submit the form for this action, you’ll be passing through the attributes<br />

for the topic as well as nested attributes for the post. With the association now<br />

defined in your Forem::Topic model, your new action will work.<br />

The next step here is defining the view for this action, which you can do by putting<br />

this code at app/views/forem/topics/new.html.erb:<br />

New Topic<br />

<br />

This view will render the partial at app/views/forem/topics/_form.html.erb, which you<br />

need to define using the code in the following listing.<br />

Listing 17.6 app/views/forem/topics/_form.html.erb<br />

<br />

<br />

<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!