简体   繁体   English

重定向到Rails中的另一个控制器

[英]Redirecting to another controller in Rails

I'm trying to redirect from one controller to another in Rails and I am getting this error: 我正在尝试从Rails中的一个控制器重定向到另一个控制器,我收到此错误:

undefined method `call' for nil:NilClass nil的未定义方法`call':NilClass

The code is pretty simple (in def create method): 代码非常简单(在def create方法中):

@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: UPD:

After some investigation, it turned out that problem was in the line respond_to do |format| 经过一番调查,结果发现问题出在了respond_to do |format| in the blog_post_comment controller. blog_post_comment控制器中。 Once I removed it, everything is OK now. 一旦我删除它,现在一切正常。

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: 在BlogPost模型中,您应该具有以下行:

has_many :blog_post_comments

And in your BlogPostComment model, you should have: 在BlogPostComment模型中,您应该:

belongs_to :blog_post

In routes.rb, you should have: 在routes.rb中,您应该:

map.resources :blog_post_comment, :has_many => 'blog_post_comments'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM