Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7688301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T19:53:19+00:00 2026-05-31T19:53:19+00:00

We have the following code working for a complex rails form with checkboxes. I’m

  • 0

We have the following code working for a complex rails form with checkboxes. I’m not really happy with the solution we have in place and I was wondering if anyone knows of a more proper way to do this in rails. All the code below is working I just want to know if there is a cleaner approach.

In my Admins controller I want to remove the need to call the following code on each update.

@user.admin.school_admin_roles.destroy_all
params[:roles].each do |school_role|
    ids = school_role.split('_')
    @user.admin.school_admin_roles.find_or_create_by_school_id_and_school_role_id(ids[0], ids[1])
end if !params[:roles].nil?

So I basically want to be able to call @user.update_attributes(params[:user]) and have rails take care of creating the needed relationships for me. I have that working with AccountRole in the form below. I want to know if there is a way to do the same thing with SchoolRole given I have an extra variable school_id in the join table.

We have the following form for editing a user and assigning roles

Screenshot of form ->
https://i.stack.imgur.com/PJwbf.png

I have the following form where an admin can edit other users and assign account based roles and school based roles via checkboxes. The account based roles were easy to implement. The school based rules are a bit complicated since the join table school_admin_roles has school_id, user_id, role_id fields. We had to implement the school roles part of the form in a rather hackish way. We have the form implemented like this – notice how we hacked together school.id.to_s+’_’+role.id.to_s into the same checkbox on school roles.

In the Admins controller’s update function we manually destroy all school_admin roles on each update then loop through the school roles params do a split on the ids on ‘-‘ then manually re-create each school based role. I really hate the way we’ve had to go about this. Could anyone shed some light on a cleaner more rails centric approach to solving this scenario?

The form –

<%= form_for @user, :url => {:controller => 'admins', :action => 'update'} do |f| %>
    <%= f.label :username %>
    <%= f.text_field :username %>

    <%= f.fields_for :admin do |uf| %>
    <div class="field">
        <%= uf.label :first_name %>
        <%= uf.text_field :first_name %>
    </div>

<label>Admin Permissions</label>  
    #account level permissions works fine
    <%= hidden_field_tag "#{uf.object_name}[account_role_ids][]"   %>
    <% AccountRole.find(:all).each do |role| %>
    <div class="account_role">
        <%= check_box_tag "#{uf.object_name}[account_role_ids][]", role.id,  @user.admin.account_roles.include?(role)%>
    <%= role.name %>
    </div>
    <% end %>

   #school level permissions a bit of a hack    
    <%= hidden_field_tag "#{uf.object_name}[school_role_ids][]"   %>
        <% SchoolRole.find(:all).each_with_index do |role, index| %>
        <div class="school_role">
        <%= check_box_tag "#{uf.object_name}[school_role_ids][]",role.id, @user.admin.school_roles.include?(role) %>
        <%= role.name %>
        <span class="advanced_box admin_permissions" <% if @user.admin.school_roles.include?(role) %>style="display:inline"<% end %>>
        <div class="content" id="perm_<%= index %>">
        <h4><%= role.name %></h4>
    <% uf.object.account.schools.each do |school|%>
    <div>
    <%= check_box_tag "roles[]", school.id.to_s+'_'+role.id.to_s, role.school_admin_roles.where(:admin_id => uf.object.id).collect(&:school_id).include?(school.id)%>
    <%= school.name %>
</div>
<% end %>
<%= link_to 'Done', '#', :class => "done" %>
</div>
<a href="#" class="open"> Advanced</a>
</span>
</div>
<% end %>
</div>
<% end %>

The controller

class AdminsController < ApplicationController
def update
    @user = User.find(params[:id])
    if  @user.update_attributes(params[:user])

      # TODO find a way to refactor this 
      @user.admin.school_admin_roles.destroy_all
      params[:roles].each do |school_role|
        ids = school_role.split('_')
        @user.admin.school_admin_roles.find_or_create_by_school_id_and_school_role_id(ids[0], ids[1])
      end if !params[:roles].nil?
      #

      flash[:notice] = "Successfully updated Admin."
      redirect_to admins_path
    else
      render "edit"
    end
  end
end

Given the following models

class User < ActiveRecord::Base
  has_one :parent
  has_one :admin
  has_many :scool_admin_roles
  has_many :account_admin_roles
end

class AccountAdminRole < ActiveRecord::Base
  before_save :set_account_id

  belongs_to :admin
  belongs_to :account_role
end

class SchoolAdminRole < ActiveRecord::Base
  belongs_to :admin
  belongs_to :school_role
  belongs_to :school
end

class SchoolRole < ActiveRecord::Base
  has_many :school_admin_roles
end


class AccountRole < ActiveRecord::Base
  has_many :account_admin_role
end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T19:53:20+00:00Added an answer on May 31, 2026 at 7:53 pm

    We refactored the code above as follows

    In the model we added accepts_nested_attributes_for :school_admin_roles, :reject_if => proc { |attr| attr[‘school_role_id’].blank? }

    and added school_admin_roles_attributes to attr_accessible

    class Admin < ActiveRecord::Base
      belongs_to :account
      belongs_to :user
    
      has_many :school_admin_roles
      has_many :school_roles, :through => :school_admin_roles
      has_many :account_admin_roles
      has_many :account_roles, :through => :account_admin_roles
    
      accepts_nested_attributes_for :account
    
      accepts_nested_attributes_for :school_admin_roles, :reject_if => proc { |attr|  attr['school_role_id'].blank? }
    
      attr_accessible :account_role_ids, :email, :first_name, :last_name, :account_id, :user_id, :account_attributes, :school_admin_roles_attributes
      default_scope where(:deleted => false)
    end
    

    We then built the form as follows

    <% index2 = 0 %>
    <% SchoolRole.find(:all).each_with_index do |role, index| %>
    <div class="school_role">
    <%= check_box_tag "school_roles[]",role.id, @user.admin.school_roles.include?(role) %>
    <%= role.name %>
    <span class="advanced_box admin_permissions" <% if @user.admin.school_roles.include?(role) %>style="display:inline"<% end %>>
    div class="content" id="perm_<%= index %>">
    <h4><%= role.name %></h4>
                                    <%  uf.object.account.schools.each do |school|%>
    <div>
    <%=    check_box_tag "#{uf.object_name}[school_admin_roles_attributes][#{index2}][school_role_id]", role.id, role.school_admin_roles.where(:admin_id => uf.object.id).collect(&:school_id).include?(school.id)%>
                                                <%= school.name %>
                                            <%= hidden_field_tag "#{uf.object_name}[school_admin_roles_attributes][#{index2}][school_id]", school.id %>
                                        </div>
                                        <% index2 += 1 %>
                                <% end %>
                                <%= link_to 'Done', '#', :class => "done" %>
                        </div>
                        <a href="#" class="open"> Advanced</a>
                    </span>
                </div>
                <% end %>
            </div>
        <% end %>
    

    Which then enabled us to refactor the controller without splitting the ids but we still have to call destroy all each time which I can live with.

    def update
        @user = User.find(params[:id])
        @user.admin.school_admin_roles.destroy_all
        if  @user.update_attributes(params[:user])
          flash[:notice] = "Successfully updated Admin."
          redirect_to admins_path
        else
          render "edit"
        end
      end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following Clojure code and I'm not sure why it's not working:
Any idea why the following code is not working mysql credentials are correct, have
On a Solaris 5.8 machine, I have the following code: [non-working code] char *buf;
I have the following code and it's working (as usual) in everything but IE.
Im trying to get debugging working without an app.config. I have the following code:
I have the follwing code (which is not working): private void Window_PreviewKeyDown(object sender, KeyEventArgs
Is there a way to implement operator->, not only operator*. To have following code
I have the following code working with a DataGrid that has two column Column_A
I have the following code working fine but the problem is that it always
I have the following code working fine, but I'm unable to add a zoom

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.