views:

201

answers:

1

Hello everyone, I have a question about ruby on rails and the process of assigning variables using the params variable passed through a form

class User
  attr_accessible :available_to_admins, :name
end

Let's say that I have a field that is only available to my admins. Assuming that you are not an admin, I am going to not display the available_to_admins input in your form.

After that, when I want to save your data I'll just do a:

User.update_attributes(params[:user])

If you are an admin, then no problem, the params[:user] is going to contain name and available_tu_admins and if you're not then only your name.

Since the available_to_admins is an attr_accessible parameter, how should I prevent non admin users from being able to inject a variable containing the available_to_admins input with their new value?

+1  A: 

a. You can check user role in controller.

class User
  # remove available_to_admins from attr_accessible
  attr_accessible :name
end

def update
  @user = User.new(params[:user])
  @user.available_to_admins = params[:user][:available_to_admins] if current_user.role == 'Admin'
end

b. You can add before_save / before_update callbacks to your model

class User
  # remove available_to_admins from attr_accessible
  attr_accessible :name
  before_save :check_role
  before_update :check_role
  def check_role
    self.available_to_admins = params[:user][:available_to_admins] if current_user.role == 'Admin'
  end
end
fl00r
Thank you very much for your answer(s) fl00r!
Julien P.