Search code examples
ruby-on-railsmongoidsimple-formrails-i18n

simple_form_for with localized, scoped routes and Mongoid (missing required keys: [:id])


I have a _form.html.haml partial for a model FileType that I want to render in my new.html.haml and edit.html.haml view.

= simple_form_for [:document_manager, file_type] do |f|
    ...

When I render this partial in the new view, this works, but when I render it in the edit view, simple_form tries to set the id of file_type to the locale param if my route. My routes look like this:

Rails.application.routes.draw do
  scope '(:locale)', locale: locale: /#{I18n.available_locales.join('|')}/ do
    namespace :document_manager do
      resources :file_types, except: [:show]
    end
  end
end

For the new view the route /en/document_manager/file_types is generated, but when I try to access the edit view I get this error:

No route matches {
  :action=>"update", 
  :controller=>"document_manager/file_types", 
  :format=>nil, 
  :id=>nil, 
  :locale=>#<FileType _id: 550198ca7462720388010000, user_file_id: nil, file_name: "...", description: "...">
} missing required keys: [:id]

How can I change the form that the id and locale parameter is set right for new and edit?

Update: A first solution that works is to remove the locale scope and store the language in the session, but for SEO, this will result in duplicate content, so a better solution would be having urls like:

  • /en/document_manager/file_types
  • /fr/document_manager/file_types
  • /de/document_manager/file_types
  • ...

Solution

  • Use a normal path, some times rails overcomplicates, in this case it should automatically use the scope you are using but as you try to use it I have only used hardcoded scopes like /en|es|fr/.

    If I were you I would use something like:

    = simple_form_for document_file_type_path, method: :post do |f|
    

    and use 2 different forms, try hardcoding your available locales like

    scope "(:locale)", :locale => /en|es|fr/ do
      resources :foos
      resources :bars
      ...
    

    EDIT

    Also looks like it is waiting for 3 parameters try:

    [:document_manager, "locale", file_type]