views:

33

answers:

4

Hi,

I'd like to protect a user-generated entry in a field after its initial creation.

I'm asking the user for a unique name when they set up a project, and I want to stop that being changeable after the creation.

Is there a way to do this in Rails? Can I set it as attr_accessible at first then switch it to to attr_protected?

Cheers

A: 

I would set it to :attr_protected and create a new "new" method:

def self.my_new(attributes = {})
  obj = new(attributes)
  obj.my_protected_attribute = attributes[:protected_attribute]
  obj
end
jordinl
A: 

Hi Les

If I were to do this I'll do it in clients end using javascripts. Ex: create a javascript function which set the text box attribute to readonly after user enter the value. As i can see doing this is client side has 2 advantages

1 - you dont want to go through a server round to make lock the value 2 - You have the flexibility of allowing user to change the value if he/she wants (by clicking a button or something)

cheers

sameera

sameera207
-1 It is 'security' risk ;). It can be secured on client side but it also must be secured on server side
klew
A: 

You could also, if you know the name of the attributes, handle this in the controller

class MyModel < ActiveRecord::Base
  attr_protected :super_cool
end

And then in the controller:

def create
  @my_model = MyModel.create(params[:my_model])
  @my_model.super_cool = params[:my_model][:super_cool] unless params[:my_model].nil?
  if @my_model.save
    ..
  else
    ..
  end
end
Jesse Wolgamott
-1 It should belong to model, not controller.
klew
@klew -- care you explain your claim? This does not seem like it's a MUST be in controller.
Jesse Wolgamott
It is model related logic and it should stay in model. If you do care about it in model, then you can use it in your controllers without thinking about it. On example, your code won't do the job if he will use some nested forms and save this object through some parent object. It this case, you have to add more logic to your controllers to know all possible cases. Remember about: fat model, skinny controllers.
klew
+2  A: 

You can add custom validation method to your model:

# Project model
validate_on_update :forbid_changing_name

def forbid_changing_name
  errors[:name] = "can not be changed!" if self.name_changed?
end
klew
That's an interesting way to solve the problem; my compliments. Your down-voting people on this answer, myself included, seems contrary to the spirit of SO.
Jesse Wolgamott
@Jesse: don't take it personaly. I don't like down-voting and I use it only when I think it really is bad answer. I hope that my another comment to your answer explains it.
klew
Thanks klew - that's a solution I'd not thought of. Cheers!
Les