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

发布于 2024-08-29 10:15:13 字数 765 浏览 4 评论 0原文

我正在尝试从 Rails 中的一个控制器重定向到另一个控制器,但收到此错误:

nil:NilClass 的未定义方法“调用”

代码非常简单(在 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

保存成功,值进入数据库。如何解决重定向失败问题?

形式:

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

UPD:

经过一番调查,发现问题出在 blog_post_comment 控制器中的 respond_to do |format| 行。一旦我删除它,现在一切都正常了。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风情万种。 2024-09-05 10:15:13

假设您有关联,您可以像这样找到您的评论:

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

然后

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

如果您没有关联,则设置方法如下:

在您的 BlogPost 模型中,您应该有以下行:

has_many :blog_post_comments

在您的 BlogPostComment 模型中,你应该有:

belongs_to :blog_post

在routes.rb中,你应该有:

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

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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文