我有以下设置:
# routes.rb
namespace :forum do
resources :sections, shallow: true do
resources :threads, shallow: true do
resources :posts
end
end
end
具有预期的型号/等。 Rails路线如下所示: 当我尝试使用
# /app/views/forum/threads/new.html.haml
# @forum_section / @forum_thread correctly set in controller
= simple_form_for [@forum_section, @forum_thread] do |f|
# some form content here
我得到了错误:
ActionView::Template::Error (undefined method `forum_section_forum_threads_path' for #<#<Class:0x00007f6af7623b80>:0x00007f6af49780b8>
Did you mean? forum_section_threads_path):
嗯-是的,我当然是那个意思。
但是必须有一个比以下更好的方法:
= simple_form_for [@forum_section, @forum_thread], url: forum_section_threads_path(@forum_section)
好一行违反DRY。
我知道,我一定在这里想念一些愚蠢的东西-帮帮我吗?
答案 0 :(得分:1)
尝试
= simple_form_for [:thread, @forum_section, @forum_thread] do |f|
# some form content here
这假设@forum_section
是Section
类的持久实例,而@forum_thread
是Thread
类的新实例。
通常,如果您的路线具有:sections
和:threads
之类的资源,则您的模型将称为Section
和Thread
。按照惯例,您的实例变量也将称为@section
和@thread
,但是它们的名称并不是那么重要。如果您的设置与此不同,Rails可能很难猜测您要生成的URL。
如果要将模型保留在相同的名称空间下,例如Forum::Section
和Forum::Thread
,则还必须更改路径助手的默认命名
namespace :forum do
resources :sections, shallow: true, as: :forum_sections do
resources :threads, shallow: true, as: :forum_threads do
resources :posts
end
end
end
答案 1 :(得分:0)
#controller
@forum_thread = Thread.new
#view
= simple_form_for [:forum, @forum_section, @forum_thread]
表单操作将为POST / sections /:id / threads