# POST /topics
# POST /topics.xml
def create
@topic = Topic.new(params[:topic])
@topic.forum_id = params[:forum_id]
@topic.user_id = logged_in_user.id
#params[:post].merge({:topic_id => @topic.id, :user_id => logged_in_user.id})
@post = Post.new(params[:post])
@post.topic = @topic
@post.user_id = logged_in_user.id
respond_to do |format|
if @topic.save && @post.save
flash[:notice] = 'Topic was successfully created.'
format.html { redirect_to forum_topic_posts_path(:topic_id => @topic, :forum_id => @topic.forum.id) }
format.xml { render :xml => @topic, :status => :created, :location => forum_topic_posts_path(:id => @topic, :form_id => @topic.forum.id) }
else
format.html { render :action => "new" }
format.xml { render :xml => @topic.errors, :status => :unprocessable_entity }
end
end
end
Refactorings
No refactoring yet !
Lachlan Sylvester
August 3, 2009, August 03, 2009 10:28, permalink
# POST /topics
# POST /topics.xml
def create
@forum = Forum.find(params[:forum_id])
@topic = @forum.topics.build(params[:topic])
@topic.user = logged_in_user
respond_to do |format|
if @topic.save
flash[:notice] = 'Topic was successfully created.'
format.html { redirect_to forum_topic_posts_path(:topic_id => @topic, :forum_id => @forum) }
format.xml { render :xml => @topic, :status => :created, :location => forum_topic_posts_path(:id => @topic, :forum_id => @forum) }
else
format.html { render :action => "new" }
format.xml { render :xml => @topic.errors, :status => :unprocessable_entity }
end
end
end
class Topic < ActiveRecord::Base
...
attr_accessor :initial_post_content
def create_initial_post
posts.create(:content => initial_post_content, :user => user)
end
after_create :create_initial_post
end
Muke Tever
August 3, 2009, August 03, 2009 18:02, permalink
Old book, eh? Have you looked up the new 'nested attributes' and accepts_nested_attributes_for ? That should handle much of this for you.
This code works, but could use some more love.
The idea is when a user creates a new "Topic" -- they automatically create a new "Post" as well ( handled by the textarea in the "new topic" form).
The code from the book I'm reviewing is outdated and you can no longer pass more than one argument to Foo.new() in rails 2.3
The commented out params[:post].merge(...) command didn't to work.