2

I have a resource that's accessible both with and without a namespace.

# routes.rb
resources :foo
namespace :admin do
  resources :foo
end

I want to use the same _form partial in both cases, but form_for requires a different argument depending upon the controller.

Should I set the form_for argument in the controllers?

# foo_controller.rb
def set_foo
  @form_for_arg = @foo
end

# admin/foo_controller.rb
def set_foo
  @form_for_arg = [:admin, @foo]
end

1 Answer 1

2

Put the common features of the form inside the partial, and wrap it in the individual form_for:

<%= form_for [:admin, foo] do |f| %>
  <%= render "foos/form", f: f %>
<% end %>

And:

<%= form_for [foo] do |f| %>
  <%= render "foos/form", f: f %>
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

Will f be available in that partial? Wouldn't I need to use render "foos/form", f: f
My mistake. My original answer didn't have the local variable passing that you need: f: f. You can also do: render partial: "foos/form", locals: { f: f } but I prefer the shorter version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.