Neil,
You’ve got to give more information about what and how it “doesn’t
work”; where are you placing that code (in a view, I assume… but I
don’t know), what does the controller method look like, what error
message are you getting (nomethod? unexpected kend?..)
This is the error:
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.login
Extracted source (around line #2):
1:
<%= comment.content %>
2:
Submitted by:<%=comment.user.login %>
The line occurs in a partial:
<%= comment.content %>
Submitted by:<%=comment.user.login %>
user.rb
class User < ActiveRecord::Base
has_many :stories
has_many :comments
has_many :stories_commented_on,
:through => :comments,
:source => :story
def to_param
“#{id}-#{login}”
end
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :story
belongs_to :user
end
story.rb
class Story < ActiveRecord::Base
after_create :create_initial_comment
validates_presence_of :name, :link
has_many :comments
belongs_to :user
def to_param
“#{id}-#{name.gsub(/\W/, ‘-’).downcase}”
end
protected
def create_initial_comment
comments.create :user => user
end
routes.rb
map.resources :comments
map.resources :stories
map.resources :users
map.resource :session
map.resources :stories, :has_many => :comments
map.resources :users, :has_many => :comments
map.connect ‘:controller/:action/:id’
map.connect ‘:controller/:action/:id.:format’
comments_controller.rb
class CommentsController < ApplicationController
def create
@story = Story.find(params[:story_id])
@comment = @story.comments.build(params[:comment])
@story.comment.save
end
def update
@comment = Comment.all
end
def new
@comment = Comment.new
end
end
stories_controller.rb
class StoriesController < ApplicationController
def index
@story = Story.all
end
def new
@story = Story.new
end
def show
@story = Story.find(params[:id])
end
def update
@story = Story.find(params[:id])
@comment = @story.comments.build(params[:comment])
@comment.save
flash[:notice] = ‘Comment submission succeeded’
redirect_to story_path(@story)
end
def create
@story = @current_user.stories.build params[:story]
@story.save
flash[:notice] = 'Story submission succeeded'
redirect_to stories_path
end
protected
def fetch_stories(conditions)
@stories = Story.find :all,
:order => ‘id ASC’,
:conditions => conditions
end
end
users_controller
class StoriesController < ApplicationController
def index
@story = Story.all
end
def new
@story = Story.new
end
def show
@story = Story.find(params[:id])
end
def update
@story = Story.find(params[:id])
@comment = @story.comments.build(params[:comment])
@comment.save
flash[:notice] = ‘Comment submission succeeded’
redirect_to story_path(@story)
end
def create
@story = @current_user.stories.build params[:story]
@story.save
flash[:notice] = 'Story submission succeeded'
redirect_to stories_path
end
protected
def fetch_stories(conditions)
@stories = Story.find :all,
:order => ‘id ASC’,
:conditions => conditions
end
end