0

假设我在我的路线中定义了以下行

resources :a, controller: 'b', as: 'a'

和以下控制器

class BController < ApplicationController
  ...
  def new
    @b = B.new
  end

  def edit
    @b = B.find(params[:id])
  end
end

有没有办法编写部分表单以便我可以在新视图和编辑视图上使用它?例如,如果我写

<%= form_for @b do |f| %>
  ...
<% end %>

Rails 给了我一个路由错误。


不优雅的解决方案

我想出了一个不优雅的解决方案来将 BController 编写为

class BController < ApplicationController
  ...
  def new
    @b = B.new
    @url = bs_path
  end

  def edit
    @b = B.find(params[:id])
    @url = b_path
  end
end

然后将表格写为

<%= form_for(@b, url: @url) do |f| %>
  ...
<% end %>

我想知道是否有更多的“Rails”方式来实现这一点,但不必写入@url 变量

4

1 回答 1

1

似乎您可能正在寻找资源:path的选项...如果我正确地遵循了您的示例,那么您有一个模型并且您想访问它或者并且能够使用...所以我觉得您想要您的路线成为B/a/a/:ida_path(instance_of_b)

resources :b, as: 'a', path: 'a'

我相信这会做你想要的。

于 2017-07-06T04:41:02.880 回答