Hello,
I’m new at Ruby on Rails, I’m using :
-Ubuntu 14.04 LTS
-Rails 4.1.2
-Ruby 2.1.2p95
-rvm 1.25.27
I’m actually following the rails guides :
http://guides.rubyonrails.org/v4.0.6/getting_started.html#getting-up-and-running
Everything was going well until the point : 5.7 Showing points.
I have checked my files several times and I can’t figure out where is my
mistake, I can submit a post and then there is no display I get the
error :
NoMethodError in Posts#show
Showing /home/jeremy/projet/blog/app/views/posts/show.html.erb where
line
#3 raised:
undefined method `title’ for nil:NilClass
Extracted source (around line #3):
123456
Title: <%= @post.title %>
Following you’ll find my files :
-config/routes.rb
Rails.application.routes.draw do
get ‘welcome/index’
The priority is based upon order of creation: first created →
highest
priority.
See how all your routes lay out with “rake routes”.
resources :posts
You can have the root of your site routed with “root”
root ‘welcome#index’
Example of regular route:
get ‘products/:id’ => ‘catalog#view’
Example of named route that can be invoked with purchase_url(id:
product.id)
get ‘products/:id/purchase’ => ‘catalog#purchase’, as: :purchase
Example resource route (maps HTTP verbs to controller actions
automatically):
resources :products
Example resource route with options:
resources :products do
member do
get ‘short’
post ‘toggle’
end
collection do
get ‘sold’
end
end
Example resource route with sub-resources:
resources :products do
resources :comments, :sales
resource :seller
end
Example resource route with more complex sub-resources:
resources :products do
resources :comments
resources :sales do
get ‘recent’, on: :collection
end
end
Example resource route with concerns:
concern :toggleable do
post ‘toggle’
end
resources :posts, concerns: :toggleable
resources :photos, concerns: :toggleable
Example resource route within a namespace:
namespace :admin do
# Directs /admin/products/* to Admin::ProductsController
# (app/controllers/admin/products_controller.rb)
resources :products
end
end
-app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
private
def post_params
params.require(:post).permit(:title, :text)
end
def show
@post = Post.find(params[:id])
end
end
-app/views/posts/new.html.erb
New Post
<%= form_for :post, url: posts_path do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :text %>
<%= f.text_area :text %>
<%= f.submit %>
<% end %> -db/migrate/20140630133544_create_posts.rb class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.text :text t.timestamps
end
end
end
-app/views/posts/show.html.erb
Title: <%= @post.title %>
Text: <%= @post.text %>
So if you can tell me what’s wrong I’ll be very happy, because I really
don’t get it.
Thanks.