0

I have a form that sets the attributes of a model, however, there is an attribute that I want to set through the code. That is, I want the user to set some attributes, but I want the program to set other attributes.

Is there any way of doing this?

Example:

If I have table with a "text" column and a "user" column, I want the user to enter the text, but I want the "user" column to be set by the program. How would I accomplish this?

2 Answers 2

2

Sure. You could do something like this:

 def create
   @something = Something.new(params[:something])
   @something.programmatically_set_attribute = "Some value"  #Here's the part that matters

   respond_to do |format|
     if @host.save
       format.html { redirect_to(@something, :notice => 'Something was successfully created.') }
       format.xml  { render :xml => @something, :status => :created, :location => @something}
     else
       format.html { render :action => "new" }
       format.xml  { render :xml => @something.errors, :status => :unprocessable_entity }
     end
   end
end

In your form, you would just leave out the field that you don't want edited by human hands. You would also have to change the update function, as well.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to ensure that only the text attribute is updateable by the user and none other you may want to use attr_accessible as follows

class MyModel < ActiveRecord::Base
  attr_accesssible :text
end

This will ensure that only the text attribute of MyModel can be updated via mass-assignment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.