Topic: Quick Question Quick Answer

I have A Blog.
The blog has many posts.
The post has a blog_id.
Is this the best way to save the blog_id?

  def create
    @post = Post.new(@params[:post])
    @blog = Blog.find(params[:id])
    if @post.save
            flash[:notice] = "Post was successfuly created into our uber engine."
      @post.update_attribute(:blog_id, @blog.id) #This is what you should be focused on!!!!
      redirect_to :controller => 'blogs', :action => 'show', :id => @blog
    else
      render :action => 'new'
    end
  end

Last edited by ldenman (2006-12-11 18:21:31)

Re: Quick Question Quick Answer

I would do something more like this:

@post = Post.new(@params[:post])
@blog = Blog.find(params[:id])

@blog.posts << @post

if @blog.save
  flash[:notice] = "Post was successfuly created into our uber engine."
  redirect_to :controller => 'blogs', :action => 'show', :id => @blog
else
  flash[:notice] = "Post was successfuly shot into deep space."
end

Re: Quick Question Quick Answer

This is updating the attribute after it saves it, which requires UPDATE call to the database. It also bypasses validation. A better way is to set the blog_id before the save:

@post.blog_id = params[:id]

Since you are fetching the blog anyway, an even better way is to use the @blog.posts.build method:

  def create
    @blog = Blog.find(params[:id])
    @post = @blog.posts.build(@params[:post])
    if @post.save
      flash[:notice] = "Post was successfuly created into our uber engine."
      redirect_to :controller => 'blogs', :action => 'show', :id => @blog
    else
      render :action => 'new'
    end
  end

This automatically sets the blog_id.

Railscasts - Free Ruby on Rails Screencasts

Re: Quick Question Quick Answer

Yep, that's better.

Re: Quick Question Quick Answer

damn, ryan. That is sexy.
I knew there was a nicer way to do it.

Gracias.