如何使用 form_for 自定义路由?

How to use form_for with customized route?

自定义路由:

resources :blog, controller: 'posts'

如何重写此行 <%= simple_form_for(@post, blog_path) do |f| %> 以消除以下错误?

TypeError in Posts#edit
ActionView::Template::Error (no implicit conversion of Symbol into Integer)

我也尝试了 <%= simple_form_for(blog_path(@post)) do |f| %>,这消除了错误,但是如果我想编辑表单,输入中保存的数据会被清空。

posts_controller

  def new
    @post = Post.new
    respond_with(@post)
  end

  def edit
  end

  def create
    @post = Post.new(post_params)
    if current_user.admin
      @post.save
      respond_with(@post)
    else
      flash[:success] = 'Get out of here.'
      redirect_to root_url
    end
  end

它可以带一个散列选项,包括url,所以像这样:

编辑:将 blog_path 更改为 blogs_pathblog_path 是显示操作,而不是创建操作,因此需要一个 id(并且不是 post 路径)。试试这个方法。

<%= simple_form_for(@post, url: blogs_path) do |f| %>

不知道这是否适用,但前几天我发现的一个非常酷的功能是 .becomes - 您可以在其中更改对象的 "class" 以便 Rails以不同的方式对待它:

This can be used along with record identification in Action Pack to allow, say, Client < Company to do something like render partial: @client.becomes(Company) to render that instance using the companies/company partial instead of clients/client.

所以...

如果你有一个 Blog 模型,并且希望每个 @post 都被这样对待(同样,我根本不知道这是否是你的设置),你可以这样做以下:

<%= simple_form_for @post.becomes(Blog) do |f| %>

不合适我会删除;对我来说很有用。


更新

如果您希望 posts_path 成为博客 (IE url.com/blog/1),您需要考虑使用路由生成器的 path 选项:

#config/routes.rb
resources :posts, path: "blog", as: :blog # -> url.com/blogs/2