views:

212

answers:

1

Hi,

I'm trying to redirect from one controller to another in Rails and I am getting this error:

undefined method `call' for nil:NilClass

The code is pretty simple (in def create method):

@blog_post_comment = BlogPostComment.new(params[:blog_post_comment])

respond_to do |format|
  if @blog_post_comment.save
    flash[:notice] = 'Comment was successfully created.'
    redirect_to(@blog_post_comment.blog_post)
  else
    render :action => "new"
  end
end

Save goes ok, the value gets into the database. How can I work around the redirect fail?

Form:

<% form_for @blog_post_comment do |f| %>
    <%= f.hidden_field :blog_post_id %>
...

UPD:

After some investigation, it turned out that problem was in the line respond_to do |format| in the blog_post_comment controller. Once I removed it, everything is OK now.

+1  A: 

Assuming you have an association, you can find your comment like this:

@blog_post = BlogPost.find(params[:blog_post_id])
@blog_post_comment = @blog_post.comments.build(params[:blog_post_comment])

And then

respond_to do |format|
  if @blog_post_comment.save
    flash[:notice] = 'Comment was successfully created.'
    redirect_to(@blog_post)
  else
    render :action => "new"
  end
end

If you don't have an association, here's how you set it up:

In your BlogPost model, you should have the following line:

has_many :blog_post_comments

And in your BlogPostComment model, you should have:

belongs_to :blog_post

In routes.rb, you should have:

map.resources :blog_post_comment, :has_many => 'blog_post_comments'
yuval
Hmm, not sure I'm getting syntax of "@blog_post.build" - how does it know that this is comment to be built?
Vitaly
Should be @blog_post.comments.build(...) I think.
Tilendor
Yeup, thanks Tilendor. Fixed.
yuval
Ok, got it. It shows an error that it can't find BlogPost by ID, I believe this is because blog_post_id is inner parameter of blog_post_comment. From Request: "blog_post_comment"=>{"body"=>"qweqwe", "blog_post_id"=>"1"}. How do I get it?
Vitaly
This would be passed through the params hash, so you could do `params['blog_post_comment']['blog_post_id']`, though something tells me there's an easier way of doing that... Let me know if that works for you.
yuval