Rails 5中的浅层,嵌套式,命名空间类

时间:2019-06-30 21:25:47

标签: ruby-on-rails ruby ruby-on-rails-5

我有以下设置:

# routes.rb

namespace :forum do
  resources :sections, shallow: true do
    resources :threads, shallow: true do
      resources :posts
    end
  end
end

具有预期的型号/等。 Rails路线如下所示: Picture of rails routes 当我尝试使用

# /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。

知道,我一定在这里想念一些愚蠢的东西-帮帮我吗?

2 个答案:

答案 0 :(得分:1)

非命名空间解决方案

尝试

= simple_form_for [:thread, @forum_section, @forum_thread] do |f|
  # some form content here

Source

这假设@forum_sectionSection类的持久实例,而@forum_threadThread类的新实例。

通常,如果您的路线具有:sections:threads之类的资源,则您的模型将称为SectionThread。按照惯例,您的实例变量也将称为@section@thread,但是它们的名称并不是那么重要。如果您的设置与此不同,Rails可能很难猜测您要生成的URL。

命名空间解决方案

如果要将模型保留在相同的名称空间下,例如Forum::SectionForum::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

Source

答案 1 :(得分:0)

#controller
@forum_thread = Thread.new

#view
= simple_form_for [:forum, @forum_section, @forum_thread]

表单操作将为POST / sections /:id / threads