2

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!

1
  • I don't think it will work Commented May 5, 2014 at 16:30

1 Answer 1

7

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| %>
Sign up to request clarification or add additional context in comments.

1 Comment

This solution worked great. However, I ended up realizing that while I wanted to avoid duplication, I did not want the admins to see different forms than the user on the front end of the application. I ended up just abstracting duplicate sections into partials and passing in the local f variable like: <%= render partial: 'form_fields', locals: { f: f } %>

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.