How can I achieve that an user could only edit some fields from a record?
For example:
A user can register on the system and select and specify username, password, etc. But a registered user can only edit his name, email and password, not his username.
I have a partial _form, which I use for new and edit functions. The partial looks like this:
<% form_for @user do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :gruebl_employee_id %><br />
<%= f.collection_select(:firma_employee_id, FirmaEmployee.find(:all).sort_by{|p| p.lastname.downcase},:id,:full_name, { :include_blank => "---keine Mitarbeiter---", :prompt => "---Bitte auswählen---"}, { :style => "width: 332px;"}) %>
</p>
<%= observe_field(:user_firma_employee_id,
:frequency => 0.25,
:url => { :action => :retrieveinfo },
:with => "'id='+value") %>
<p>
<%= f.label :username %><br />
<%= f.text_field :username %>
</p>
<p>
<%= f.label :admin, "Administrator ?" %><br />
<%= f.check_box :admin %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br />
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</p>
<p><%= f.submit %></p>
<%end%>
What I am trying to do is block the user from changing the employee and the username attribute.
Thanks in advance.
Take care of this in several places.
First, use attr_accessible in the User model, to include only those you want the user to edit:
attr_accessible :name, :email, :password, :password_confirmation #...
Then in the form partial, only shows the username field when showing the signup form:
<% if @user.new_record? %> <%= f.text_field :username %> <% end %>
Lastly, in the create action, manually set the username field, since it's now in the attr_accessible list you cannot mass assign it:
@user = User.new(params[:user]) @user.username = params[:user][:username]
Please keep in mind if username is able to be set through mass assignment, even if you disable the username field in the form, it still can be modified (it's easy to change the field value in the form on the client side). That's why we have to use the attr_accessible for pretection.
Edit: noticed your partial, it's better to protect the admin field as username, otherwise users are able to set themselves as admin by changing the fields value on client side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With