ruby-on-rails - redirect_to , Controller 和模型之间的关系

标签 ruby-on-rails

我生成了一个脚手架,它制作了一个如下所示的 Controller (我删除了一些代码,但它仍然有效)。

  def create
    @post = Post.new(params[:post])

    if @post.save
      redirect_to @post
    end
  end

这会导致它重定向到/posts/id ,一切正常。

但我不明白这是如何工作的。 @post 是模型类的实例,那么它如何知道应该重定向到哪个 Controller 和操作呢?我没有看到任何地方明确定义了这种关系(在 Post 模型和 PostsController 之间)。

我尝试在没有脚手架的情况下从头开始复制此内容,但收到有关无法找到与我定义的模型关联的 url_for 的错误。即使我在 routes.rb 中使用 resources 定义路由。

最佳答案

当您调用redirect_to时它通过调用 _compute_redirect_to_location 来计算路径方法

并达到 else that method中的声明

并调用url_for方法其中 reaches else 也是如此。

并调用polymorphic_path (和polymorphic_url)here .

这里convert_to_model(record) method has been called .

哪里 record == @post

计算inflection你会reach else 它是:singular

之后你会reach build_named_rout_call

并调用 ActiveModel::Naming.singular_route_key(@post) 。 您将得到['post']

route << routing_type(options) 之后您的路线是['post', :url]

推杆 @post into args send("post_url", args)post_path(@post) 相同

如果我有什么地方说错了,我很抱歉。我希望这能让您了解redirect_to @post .

关于ruby-on-rails - redirect_to , Controller 和模型之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493502/

相关文章:

ruby-on-rails - 无法使用 Rails 4 和 bootstrap-sass gem 在 Heroku 上使用 CSS

ruby-on-rails - Rails 将 DateTime 转换为 'where' 查询中的日期

mysql - count 方法根据条件中的日期返回不同的值

mysql - 在 Ruby on Rails 应用程序中安全删除用户表

ruby-on-rails - 如何更改resque的默认 sleep 时间(5s)?

ios - NSErrorFailingURLStringKey (kCFErrorDomainCFNetwork error -1017) 针对特定请求

ruby-on-rails - Rails/Puma 带有 Apache HTTPD 代理吗?

ruby-on-rails - 如何在 Ruby 中将图像写入到文件系统的 url 中?

ruby-on-rails - 如何将 Ruby 数组从我的 Heroku 控制台导出为 CSV?

ruby-on-rails - 如何在 redis rails 中订阅多个发布者?