如何使用新动作的参数声明Rails资源? [英] How to declare a rails resource with a parameter for new action?
问题描述
我有一个名为 Entree 的模型,为此 new
操作需要一个参数,即另一个名为 Cave 的模型的ID。强>。我不想将Entree嵌套在Cave中,因为Cave已经被嵌套。
我所做的是在 routes.rb
中声明资源Entree,如下所示。 :
I have a model named Entree for which the new
action needs a parameter, the id of another model named Cave. I don't want to nest Entree in Cave since Cave is already nested.
What I did was declaring the resource Entree as follow in routes.rb
:
resources :entrees, :except => [:new]
match "/entrees/new/:id", :to => "Entrees#new", :as => 'new_entree'
可以,但是问题是当 create
操作,我要使用无效输入再次显示该页面。但是由于没有 new
操作,因此我必须执行 redirect_to new_entree_path
,这不会保留用户的输入。
That works, but the problem is when there's an error in the create
action, I want to display the page again with the invalid input. But since there's no new
action, I must do a redirect_to new_entree_path
, which does not keep the user input.
我尝试了以下(最简单的)路线:
I have tried the following (simplest) route:
resources :entrees
但是路径 http:// localhost:3000 / entrees / new / 32
返回错误:
没有路线匹配[GET] / entrees / new / 32
问题是,如何使用 new
操作?
The question is, how can I declare the Entree resource in the routes file with a parameter for the new
action ?
推荐答案
我不确定这是否是黑客,但是以下方法可以解决似乎比2级嵌套更干净。
I'm not sure if that's a hack or not, but the following works and seems cleaner than 2-levels nesting.
resources :entrees, :except => [:new] do
collection do
get 'new/:id', :to => "entrees#new", :as => 'new'
end
end
现在我可以做一个呈现新
,而不是 redirect_to
。
我必须说我一定是问错了我的问题,我的坏。
Now I can do a render "new"
instead of a redirect_to
.
I must say that I must have asked my question wrongly, my bad.
这篇关于如何使用新动作的参数声明Rails资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!