Search code examples
ruby-on-railsruby-on-rails-3formbuilder

How to selectively display fields in new/edit views with custom form builder in rails 3.2.12?


In our rails 3.2.12 app, we would like to selectively display fields in new/edit views (using simple_form) based on the access rules. For example, for sales, only customer's name and phone# can be displayed. Since we don't know what the access rule is going to be, we need to dynamically construct the view at run time. One way to accomplish this is to use if in the views and this would make views messy. We thought customform build might help. After reading a few posts online about custom form builder, we still did not have much clue. Can someone provide details about how to implement this with customform builder? Thanks for help!

UPDATE: Since we don't know what the access rule is going to be, we need to dynamically construct view at run time.


Solution

  • Usually a custom form builder is used to change the structure of the form's HTML more than to control field access.

    A couple of suggestions to "clean up" the views:

    1. Using SimpleForm will let you handle form fields/labels as a unit, making it easier to exclude a field using only something like = form_builder.input :credit_card_number if current_user.admin?.
    2. For a more application-wide solution CanCan can help you manage authorization and roles.

    Edit:

    Based on your comments, it sounds like the following could be a good approach for you if all the columns are treated the same and you don't need to change their order (using HAML, but you could change it to ERB if necessary):

    = simple_form_for @model do |f|
       = f.error_notification
       - @model.columns_available_for(current_user).each do |column|
          = f.input column