如何在 Rails 中将两个控制器与一个模型一起使用 [英] How to use two controllers with one model in Rails
问题描述
我有一个订单模型.客户通过 Orders 控制器与 Order 模型交互.管理员通过 Purchases 控制器与 Order 模型交互.
I have an Order model. Customers interact with the Order model through an Orders controller. Admins interact with the Order model through a Purchases controller.
大多数情况下它都在工作,除非发生这种情况:
Mostly it's working, except this happens:
- 管理员用户转到 new_purchase_path
- 该应用在购买控制器中使用创建"操作,如预期
- 然后应用程序使用订单控制器中的新"操作(而不是购买控制器)
- App 然后呈现app/purchases/new"视图(不是app/orders/new"视图),尽管它已切换到使用订单控制器
- 在管理员创建订单后,应用程序会呈现使用订单控制器的app/orders/show"视图
我真正需要做的是:
- 管理员用户转到 new_purchase_path
- 该应用然后使用购买控制器中的创建"操作
- 该应用然后使用购买控制器中的新"操作
- 然后应用呈现app/purchases/new"视图
- 在管理员创建订单后,应用程序会呈现使用购买控制器的app/purchases/show"视图
在 app/controllers/purchases_controller.rb 我有这个:
In app/controllers/purchases_controller.rb I have this:
def new
@purchase = Order.new
respond_with @purchase
end
如果尝试过类似...的变体
If have tried variations like...
def new
@purchase = Order.new
respond_with @purchase, :controller => :purchases
end
...但没有任何类似的记录用于 response_with,自然它不起作用.我能做什么?
...but nothing like that is documented for respond_with, and naturally it doesn't work. What can I do?
推荐答案
这个问题的答案与你的最后一个问题.我已经更新了 我的答案,但简而言之,问题不在于 respond_with
(正如@jiri-pospisil 指出的那样,你并不真正需要),而是你的表单由simple_form_for
.该表单中的操作 url 默认为 /orders
,因为 @purchase
是 Order
类的实例.
The answer to this question is related to your last question. I've updated my answer there, but in a nutshell, the problem is not with respond_with
(which as @jiri-pospisil points out you don't really need) but with your form generated by simple_form_for
. The action url in that form defaults to /orders
because @purchase
is an instance of the class Order
.
要解决该问题,请以以下形式指定网址:
To fix that problem, specify the url in the form:
= simple_form_for @purchase, :as => :purchase, :url => purchases_path(@purchase) do |f|
= f.error_notification
= f.input :name
= f.button :submit
然后你会发现你有另一个问题:新订单(购买)创建后,respond_with
会重定向到OrdersController的
show
动作代码>.要解决此问题,您可以使用 location
选项:
You'll then find that you have another problem: after the new order (purchase) is created, respond_with
will redirect to the show
action of OrdersController
. To fix that, you can use the location
option:
def create
@purchase = Order.new(params[:purchase])
if @purchase.save
respond_with(@purchase, :location => purchases_path(@purchase))
...
此时您可能会知道,以这种方式为单个模型使用两个控制器会有些复杂,因此您可能需要考虑 命名空间.
As you can probably tell at this point, using two controllers for a single model this way becomes somewhat convoluted, so you might want to consider namespaces instead.
这篇关于如何在 Rails 中将两个控制器与一个模型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!