Question

I'm trying to avoid code duplication between Admin forms and Regular User forms for the same resource.

I would like to be able to use one form for both, by doing something like:

<% if current_user.admin? %>
  <%= form_for([:admin,@post], :html => {class: "form"}) do |f| %>
<% else %>
  <%= form_for @post, html: { class: 'form' } do |f| %>
<% end %>

then include fields that only the admin should see via if statements in the body of the form.

This approach doesn't work, I think because the <% end %> is ending the form.

Is there a way to do this? Does this approach even make sense?

Thanks!

Was it helpful?

Solution

Try to move the code to your helper may help:

#YourHelper.rb
def form_for_admin(condition, &block)
    if condition
        form_for [:admin, @post], :html => {class: "form"}, &block
    else
        form_for @post, html: { class: 'form' }, &block
    end
end

and use:

<%= form_for_admin current_user.admin? do |f| %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top