Redirecting to another controller in Rails

I am trying to redirect from one controller to another in Rails, and I get this error:

undefined `call 'method for nil: NilClass

The code is pretty simple (in the 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 is normal, the value goes to the database. How can I get around redirect failure?

the form:

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

UPD:

After some research, it turned out that the problem was in the line respond_to do |format| in the blog_post_comment controller. As soon as I remove it, now everything is in order.

+4
source share
1 answer

Assuming you have a connection, you can find your comment as follows:

 @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 is 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' 
+1
source

Source: https://habr.com/ru/post/1306834/


All Articles