Table of Content
Building the photo controller and view
We want RESTful URLs for our photo resource. Here is the routes.rb
file.
It is time to create the contorller.
1$ rails generate controller photos
The controller
views/photos/new.html.erb
Let’s try the function in browser with the following steps.
- In terminal, in the current project, run
rails server
. - Open
http://0.0.0.0:3000/photos/new
in web browser. - Select an image file and put in the title.
- Click the ‘Upload Photo’ button.
- Now we should see an error of
NoMethodError
. - If we check the URL, it is redirected to the photo showing URL with the newly created photo ID.
- This is normal because we haven’t implemented the
show
method in controller yet.
Then we add the show feature
The photos_controller.rb
And its related view: views/photos/show.html.erb
Since the edit form shares the same code from the create form, we will extract the form into a common file.
Move the entire form_for
block to a new file: views/photos/_form.html.erb
Now the views/photos/new.html.erb
becomes
And the views/photos/edit.html.erb
file
Optionally we may want to let site admin edit the photo from the user interface, we can do that by adding a link to the edit path in the views/photos/show.html.erb
file.
1<%= link_to 'Edit', edit_photo_path(@photo) %>
And the edit
and update
controller method in the photos_controller.rb
file.
Let’s try the function in browser and we should be able to create and edit photos. Here is a screenshot of the editing screen:
What’s next? We’re going to take a look at “Using partial file”.